微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

在线程中无法将Python Popen写入stdin

如何解决在线程中无法将Python Popen写入stdin

| 我正在尝试编写一个程序,该程序分别同时读取和写入进程的std(out / in)。但是,似乎无法在线程中写入程序的stdin。这是相关的代码位:
import subprocess,threading,queue

def intoP(proc,que):
    while True:
        if proc.returncode is not None:
            break
        text = que.get().encode() + b\"\\n\"
        print(repr(text))      # This works
        proc.stdin.write(text) # This doesn\'t.


que = queue.Queue(-1)

proc = subprocess.Popen([\"cat\"],stdin=subprocess.PIPE)

threading.Thread(target=intoP,args=(proc,que)).start()

que.put(\"Hello,world!\")
怎么了,有没有办法解决? 我在Mac OSX上运行python 3.1.2,已确认它可以在python2.7中使用。     

解决方法

        答案是-缓冲。如果您添加一个
proc.stdin.flush()
proc.stdin.write()
调用之后,您会如预期的那样看到“ Hello,world!\”打印到控制台(通过子进程)。     ,        我将proc.stdin.write(text)更改为proc.communicate(text),这在Python 3.1中有效。     

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。