如何在 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"])
关于python - 如何执行程序或调用系统命令?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51187528/