我有一个程序myshell.exe,我需要通过python与它交互(向它发送命令并读取结果)。
问题是我只能运行myshell.exe
一次(不能包含popen并在循环中通信)
我尝试过popen
和popen.communicate()
,但似乎运行了myshell.exe
,发送了命令,然后退出了进程。
# settin up the command
p = Popen("myshell.exe", stdout=PIPE, stdin=PIPE, stderr=PIPE, shell=True)
# sending something (and getting output)
print p.communicate("run");
此时,从打印输出中,我可以看到我的myshell.exe
已经退出(我打印了一条再见消息)。
如果有什么办法的话,有什么想法吗?谢谢
正如您在Popen.communicate
文档中所读到的,它将等待myshell.exe
退出后再返回。
使用p.stdout
和p.stdin
与进程通信:
p.stdin.write("run")
print p.stdout.read(1024)
CCD_ 10和CCD_。你可以在一个循环中对它们进行读写,只需将p = Popen(...)
部分留在外面:
p = Popen("myshell.exe", stdout=PIPE, stdin=PIPE, stderr=PIPE, shell=True)
for i in range(3):
p.stdin.write("run")
print p.stdout.read(16)
p.terminate()
这是假设myshell.exe
的行为正如您所期望的那样(例如,在发送第一个命令后不会退出)。