使用python运行Windows Shell命令 [英] Running windows shell commands with python
问题描述
我们如何使用Python与OS Shell进行交互? 我想通过python运行Windows cmd命令.如何实现?
How can we interact with OS shell using Python ? I want to run windows cmd commands via python. How can it be achieved ?
推荐答案
应该使用较新的subprocess.check_output
和类似命令替换os.system
.有关详细信息,请参见此页面.虽然我无法在Windows上进行测试(因为我无权访问任何Windows计算机),但以下方法应该可以工作:
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 (because I don't have access to any Windows machines), the following should work:
from subprocess import check_output
check_output("dir C:", shell=True)
check_output
返回命令的输出字符串.另外,subprocess.call
仅运行命令并返回命令状态(如果一切正常,通常为0).
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).
还请注意,在python 3中,该字符串输出现在为bytes
输出.如果要将其更改为字符串,则需要类似
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()
如有必要,您可以告诉它对程序输出进行编码.默认值为utf-8
,通常可以正常使用,但其他标准选项为这里.
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.
还请注意,@ bluescorpion在注释中表示Windows 10需要尾随反斜杠,如check_output("dir C:\\", shell=True)
所示.需要双反斜杠,因为\
是python中的特殊字符,因此必须为转义了. (还要注意,如果\
是字符串的最后一个字符,即使给字符串加上r
前缀也无济于事-r"dir C:\"
是语法错误,但r"dir C:\ "
不是).
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 r
doesn't help if \
is the very last character of the string — r"dir C:\"
is a syntax error, though r"dir C:\ "
is not.)
这篇关于使用python运行Windows Shell命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!