在后台运行一个.exe,然后通过python在其中输入内容

2024-05-23 19:15:06 发布

您现在位置:Python中文网/ 问答频道 /正文

我有个计划,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已经退出(我有一个打印的再见消息)。在

有什么办法吗? 谢谢。在


Tags: the命令进程stdinstdoutexecommand计划
1条回答
网友
1楼 · 发布于 2024-05-23 19:15:06

正如您可以在^{}文档中阅读的那样,它将等到myshell.exe退出后再返回。在

使用p.stdoutp.stdin与进程通信:

p.stdin.write("run")
print p.stdout.read(1024)

p.stdinp.stdout是常规文件对象。您可以在一个循环中读写它们,只需将p = Popen(...)部分放在外面:

^{pr2}$

这假设myshell.exe的行为与您预期的一样(例如,在发送第一个命令后不退出)。在

相关问题 更多 >