Python子进程交互,为什么我的进程可以使用Popen.communicate,但不能使用Popen.stdout.read()? [英] Python subprocess interaction, why does my process work with Popen.communicate, but not Popen.stdout.read()?

查看:238
本文介绍了Python子进程交互,为什么我的进程可以使用Popen.communicate,但不能使用Popen.stdout.read()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用subprocess模块与使用Python的命令行聊天机器人进行通信. (http://howie.sourceforge.net/使用已编译的win32二进制文件,我有我的理由!)

I am trying to communicate with a command-line chat bot with Python using the subprocess module. (http://howie.sourceforge.net/ using the compiled win32 binary, I have my reasons!)

这有效:

proc = Popen('Howie/howie.exe', stdout=PIPE,stderr=STDOUT,stdin=PIPE)
output = proc.communicate()

但是Popen.communicate等待进程终止(并将其发送给EOF?),我希望能够与之交互.显然的解决方案是像这样读取stdout/写stdin:

But Popen.communicate waits for the process to terminate (and sends it EOF?), I want to be able to interact with it. The apparent solution for this was to read stdout / write stdin like so:

这不起作用:

proc = Popen('Howie/howie.exe', stdout=PIPE,stderr=STDOUT,stdin=PIPE)
while True: print proc.stdout.readline()

(请注意,我实际上使用的是基于 http://code.activestate.com的更复杂的代码/recipes/440554/,但问题是相同的.)

(Note that I am actually using more complex code based on http://code.activestate.com/recipes/440554/ but the issue is the same.)

问题是,第二种方法非常适合与cmd通信,但是当我运行chatbot时,什么也没有.所以我的问题是,捕获输出与使用Popen.communicate()有何不同?

The problem is, the second approach works perfectly for communicating to cmd, but when I run the chatbot, nothing. So my question is, how is this different in capturing output to using Popen.communicate()?

即在运行chatbot之前,我可以使用第二种方法正常使用命令行,直到此时我停止接收输出.使用第一种方法可以正确显示该bot的前几行输出,但使我无法与其进行交互.

i.e. I can use the second approach to use the command line as per normal, until I run the chatbot, at which point I stop receiving output. Using the first approach correctly displays the first few lines of output from the bot, but leaves me unable to interact with it.

推荐答案

两者之间的主要区别在于,send()在发送数据后关闭stdin.我不知道您的特殊情况,但是在很多情况下,这意味着如果某个进程正在等待用户输入的结束,则在使用communication()时他将获得该信息,而在代码阻塞时将永远不会获得该信息. read()或readline().

One major difference between the two is that communicate() closes stdin after sending the data. I don't know about your particular case, but in many cases this means that if a process is awaiting the end of the user input, he will get it when communicate() is used, and will never get it when the code blocks on read() or readline().

尝试先添加Popen.stdin.close(),看看它是否影响您的情况.

Try adding Popen.stdin.close() first and see if it affects your case.

这篇关于Python子进程交互,为什么我的进程可以使用Popen.communicate,但不能使用Popen.stdout.read()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆