您如何在Python脚本中调用外部命令(就像我在Unix Shell或Windows命令提示符下键入的一样)?
ask by freshWoWer translate from soLook at the subprocess module in the standard library:
(查看标准库中的子流程模块:)
import subprocess
subprocess.run(["ls", "-l"])
The advantage of subprocess
vs. system
is that it is more flexible (you can get the stdout
, stderr
, the "real" status code, better error handling, etc...).
(与system
相比, subprocess
的优势在于它更灵活(您可以获取stdout
, stderr
,“真实”状态代码,更好的错误处理等)。)
The official documentation recommends the subprocess
module over the alternative os.system()
:
(官方文档建议使用替代os.system()
的subprocess
模块:)
The
subprocess
module provides more powerful facilities for spawning new processes and retrieving their results;(
subprocess
模块提供了更强大的功能来生成新流程并检索其结果。)using that module is preferable to using this function [os.system()
].(使用该模块优于使用此功能[
os.system()
]。)
The Replacing Older Functions with the subprocess Module section in the subprocess
documentation may have some helpful recipes.
(子 subprocess
文档中的用子流程模块替换较早的功能部分可能有一些有用的方法。)
For versions of Python before 3.5, use call
:
(对于3.5之前的Python版本,请使用call
:)
import subprocess
subprocess.call(["ls", "-l"])