使用 python 运行 windows shell 命令

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14894993/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 12:46:54  来源:igfitidea点击:

Running windows shell commands with python

pythonwindowsoperating-systemshell

提问by Avi Mehenwal

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

我们如何使用 Python 与 OS shell 交互?我想通过 python 运行 windows cmd 命令。如何实现?

采纳答案by Mike

The newer subprocess.check_outputand similar commands are supposed to replace os.system. See this pagefor details. While I can't test this on Windows (because I don't have access to any Windows machines), the following should work:

较新subprocess.check_output和类似的命令应该替换os.system. 有关详细信息,请参阅此页面。虽然我无法在 Windows 上对此进行测试(因为我无法访问任何 Windows 机器),但以下应该有效:

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

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

check_output返回命令的输出字符串。或者,subprocess.call只需运行命令并返回命令的状态(如果一切正常,通常为 0)。

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

另请注意,在 python 3 中,现在bytes输出该字符串输出。如果你想把它改成一个字符串,你需要像

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

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

如有必要,您可以告诉它您的程序输出的编码类型。默认为utf-8,这通常可以正常工作,但其他标准选项在这里

Also note that @bluescorpion says in the comments that Windows 10 needs a trailing backslash, as in check_output("dir C:\\", shell=True). The double backslash is needed because \is a special character in python, so it has to be escaped. (Also note that even prefixing the string with rdoesn't help if \is the very last character of the string — r"dir C:\"is a syntax error, though r"dir C:\ "is not.)

另请注意,@bluescorpion 在评论中说 Windows 10 需要尾随反斜杠,如check_output("dir C:\\", shell=True). 需要双反斜杠,因为它\是python中的特殊字符,因此必须对其进行转义。(另请注意,r如果\是字符串的最后一个字符,即使给字符串添加前缀也无济于事-r"dir C:\"是语法错误,但r"dir C:\ "不是。)

回答by Timidger

You would use the os module system method.

您将使用 os 模块系统方法

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

你只要把命令的字符串形式放进去,返回值就是windows环境变量COMSPEC

For example:

例如:

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

os.system('python') 打开 windows 命令提示符并运行 python 解释器

os.system('python') example

os.system('python') 示例

回答by srinivas-beerge

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

回答by crizCraig

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

重构@srini-beerge 的答案,获取输出和返回码

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)

回答by ccy

You can use the subprocesspackage with the code as below:

您可以使用subprocess带有以下代码的包:

import subprocess
cmdCommand = "python test.py"   #specify your cmd command
process = subprocess.Popen(cmdCommand.split(), stdout=subprocess.PIPE)
output, error = process.communicate()
print output

回答by Rahul kuchhadia

Simple Import os package and run below command.

简单的导入 os 包并运行下面的命令。

import os
os.system("python test.py")