在后台运行.exe,并通过python将内容键入其中

  • 本文关键字:python 运行 后台 exe python popen
  • 更新时间 :
  • 英文 :


我有一个程序myshell.exe,我需要通过python与它交互(向它发送命令并读取结果)。

问题是我只能运行myshell.exe一次(不能包含popen并在循环中通信)

我尝试过popenpopen.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.stdoutp.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的行为正如您所期望的那样(例如,在发送第一个命令后不会退出)。

最新更新