使用 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"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屋!