Look 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
模块提供了更强大的功能来生成新流程并检索其结果。)
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"])
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…