如何使用python与命令行程序进行通信?
问题描述:
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进行通信。如何使用python与命令行程序进行通信?
谢谢。 (使用Windows平台)
答
的docs on communicate()
解释:与过程
交互:将数据发送至标准输入。从stdout和 stderr中读取数据,直到达到文件结束。等待进程终止。
communicate()
块一旦输入已发送,直到程序完成执行。在你的例子中,程序在发送"1"
后等待更多的输入,但是Python在它到达下一行之前等待它退出,这意味着整个事件都会死锁。
如果您想要互换地读写很多,请拨打make pipes至stdin
/stdout
,然后向其中写入/读取。
+0
感谢它帮助我了解下一步该做什么。 – user1717522
+1
@ user1717522 - 如果您发现问题的答案令人满意,则应将其标记为已接受。 – root
你为什么不在这里粘贴接收器进程的相关部分? – Dhara
可以尝试类似'proc.stdin.write(data_to_write)' – avasal
这是重复的。 –