如何从Python执行程序或调用系统命令 [英] How to execute a program or call a system command from Python
问题描述
如何在Python脚本中调用外部命令(就像我在Unix shell或Windows命令提示符下键入的一样)?
How do you call an external command (as if I'd typed it at the Unix shell or Windows command prompt) from within a Python script?
推荐答案
使用 子过程
标准库中的模块:
Use the subprocess
module in the standard library:
import subprocess
subprocess.run(["ls", "-l"])
subprocess.run
在 os.system
上是更加灵活(您可以获取 stdout
, stderr
,真实"状态代码,更好的是错误处理等).
The advantage of subprocess.run
over os.system
is that it is more flexible (you can get the stdout
, stderr
, the "real" status code, better error handling, etc...).
甚至 os.system
的文档建议改用 subprocess
:
subprocess
模块提供了更强大的功能来生成新流程并检索其结果.使用该模块比使用此功能更可取.请参见用子流程模块替换旧功能部分.="https://docs.python.org/library/subprocess.html" rel ="noreferrer">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
:
On Python 3.4 and earlier, use subprocess.call
instead of .run
:
subprocess.call(["ls", "-l"])
这篇关于如何从Python执行程序或调用系统命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!