Running windows shell commands with python

2019-01-03 14:05发布

How can we interact with OS shell using Python ? I want to run windows cmd commands via python. How can it be achieved ?

5条回答
Bombasti
2楼-- · 2019-01-03 14:37

Refactoring of @srini-beerge's answer which gets the output and the return code

import subprocess
def run_win_cmd(cmd):
    result = []
    process = subprocess.Popen(cmd,
                               shell=True,
                               stdout=subprocess.PIPE,
                               stderr=subprocess.PIPE)
    for line in process.stdout:
        result.append(line)
    errcode = process.returncode
    for line in result:
        print(line)
    if errcode is not None:
        raise Exception('cmd %s failed, see above for details', cmd)
查看更多
何必那么认真
3楼-- · 2019-01-03 14:42
import subprocess
result = []
win_cmd = 'ipconfig'(curr_user,filename,ip_address)
process = subprocess.Popen(win_cmd,
shell=True,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE )
for line in process.stdout:
    print line
result.append(line)
errcode = process.returncode
for line in result:
    print line
查看更多
疯言疯语
4楼-- · 2019-01-03 14:54

You can use the subprocess package with the code as below:

import subprocess
cmdCommand = "python test.py"   #specify your cmd command
process = subprocess.Popen(cmdCommand.split(), stdout=subprocess.PIPE)
output, error = process.communicate()
print output
查看更多
欢心
5楼-- · 2019-01-03 14:57

The newer subprocess.check_output and similar commands are supposed to replace os.system. See this page for details. While I can't test this on Windows, the following should work:

from subprocess import check_output
check_output("dir C:", shell=True)

check_output returns a string of the output from your command. Alternatively, subprocess.call just runs the command and returns the status of the command (usually 0 if everything is okay).

Also note that, in python 3, that string output is now bytes output. If you want to change this into a string, you need something like

from subprocess import check_output
check_output("dir C:", shell=True).decode()

If necessary, you can tell it the kind of encoding your program outputs. The default is utf-8, which typically works fine, but other standard options are here.

查看更多
趁早两清
6楼-- · 2019-01-03 15:04

You would use the os module system method.

You just put in the string form of the command, the return value is the windows enrivonment variable COMSPEC

For example:

os.system('python') opens up the windows command prompt and runs the python interpreter

os.system('python') example

查看更多
登录 后发表回答