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

标签 python shell terminal subprocess command

如何在 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"])

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

相关文章:

python - Pygame 运行游戏的速度非常慢

python - Pandas :在多列上交叉制表,然后按 Groupby

python - 将一对元组与元组对列表进行比较

linux - 一个 "try"的 shell 脚本

c - 如何将 printf 输出从应用程序重定向到执行应用程序的脚本?

linux - 如何在 shell 行中捕获选项卡按钮?

Ruby 程序在终端中无法正常运行

python - setup.py egg_info"尝试安装 beautifulsoup 时失败,错误代码为 1

bash脚本: Overwrite output without filling scrollback

python - 命令行参数中的空格。无法正确读取 "C:\Program Files"