【发布时间】:2011-01-19 19:54:18
【问题描述】:
我有一个在命令行上运行良好的命令。它有很多参数,例如cmd --thing foo --stuff bar -a b input output
我想从 python 运行它并等待它完成。当脚本将内容打印到stdout 和stderr 时,我希望它立即显示给用户。
什么是正确的模块?
我试过了:
import commands
output = commands.getoutput("cmd --thing foo --stuff bar -a b input output")
print output
这很好用,除了 stdout 直到最后才返回。
import os
os.system("cmd --thing foo --stuff bar -a b input output")
这会在 cmd 实际完成时打印所有输出。
import subprocess
subprocess.call(["cmd", "--thing foo", "--stuff bar", "-a b", "input", "output"])
这并没有以某种方式正确传递参数(我无法找到确切的问题,但cmd 拒绝了我的输入)。如果我将echo 作为第一个参数,它会打印出当我将其直接粘贴到终端时完美运行的命令。
import subprocess
subprocess.call("cmd --thing foo --stuff bar -a b input output")
和上面的完全一样。
【问题讨论】:
标签: python unix subprocess