我有一个在命令行上运行良好的命令。它有许多参数,例如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")
当命令实际完成时,这将打印所有输出。
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")
与上述内容完全相同。
subprocess
似乎没有按照返回的输出进行打印。我能让它发生吗? - Paul Tarjan