📜  python - 如何执行程序或调用系统命令? - Python 代码示例

📅  最后修改于: 2022-03-11 14:46:15.793000             🧑  作者: Mango

代码示例1
Use the subprocess module in the standard library:

import subprocess subprocess.run(["ls", "-l"]) 
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...).

Even the documentation for os.system recommends using subprocess instead:

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 the subprocess documentation for some helpful recipes.

On Python 3.4 and earlier, use subprocess.call instead of .run:

subprocess.call(["ls", "-l"])