python - 如何执行程序或调用系统命令?

如何在 Python 中调用外部命令,就像在 shell 或命令提示符中键入一样?

最佳答案

使用 subprocess标准库中的模块:

import subprocess
subprocess.run(["ls", "-l"])

subprocess.run的优势|超过 os.system是它更灵活(你可以得到 stdoutstderr , "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 the subprocess documentation for some helpful recipes.

在 Python 3.4 及更早版本中,使用 subprocess.call 而不是 .run:

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

https://stackoverflow.com/questions/89228/

相关文章:

python - 如何安全地创建嵌套目录?

python - 如何列出目录的所有文件?

python - 如何按值对字典进行排序?

python - @staticmethod 和 @classmethod 之间的区别

python - 如何检查列表是否为空?

python - 在 'for' 循环中访问索引

python - 了解切片

python - Python 是否有字符串 'contains' 子字符串方法?

python - Python 的列表方法 append 和 extend 有什么区别?

python - 在函数中使用全局变量