如何在 Python 中调用外部命令,就像在 shell 或命令提示符中键入一样?
最佳答案
使用 subprocess
标准库中的模块:
import subprocess
subprocess.run(["ls", "-l"])
subprocess.run
的优势|超过 os.system
是它更灵活(你可以得到 stdout
, stderr
, "real" status code ,更好的 error handling 等...)。
偶数 the documentation for os.system
建议使用 subprocess
代替:
The
subprocess
module provides more powerful facilities for spawning new processes and retrieving their results; using that module is preferable to using this function. See the Replacing Older Functions with the subprocess Module section in thesubprocess
documentation for some helpful recipes.
在 Python 3.4 及更早版本中,使用 subprocess.call
而不是 .run
:
subprocess.call(["ls", "-l"])
https://stackoverflow.com/questions/89228/