如何使用python与命令行程序进行通信?

时间:2012-10-15 11:26:41

标签: python windows cmd subprocess communicate

import subprocess
import sys

proc = subprocess.Popen(["program.exe"], stdin=subprocess.PIPE) #the cmd program opens
proc.communicate(input="filename.txt") #here the filename should be entered (runs)
#then the program asks to enter a number:
proc.communicate(input="1") #(the cmd stops here and nothing is passed)
proc.communicate(input="2") # (same not passing anything)

如何使用python传递和与cmd通信。

感谢。 (使用Windows平台)

1 个答案:

答案 0 :(得分:5)

docs on communicate()解释一下:

  

与流程交互:将数据发送到stdin。从stdout和。读取数据   stderr,直到达到文件结尾。等待进程终止。

一旦输入被发送,

communicate()就会阻塞,直到程序完成执行。在您的示例中,程序在发送"1"之后等待更多输入,但Python在它到达下一行之前等待它退出,这意味着整个事情都会死锁。

如果您想要互换地阅读和书写,make pipesstdin / stdout并写入/读取它们。