使用管道进行交互通信是行不通的。我也试过了。我做错什么了?

2024-04-18 21:34:26 发布

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

有一个父级和一个子级,它们通过管道连接。父级对子级执行非阻塞读取,并对子级的管道执行阻塞写入。另外,对于非阻塞读取,我使用带超时的select()。你知道吗

父级的代码:

import os
import sys
from time import sleep
import signal
import fcntl
from select import select
from subprocess import Popen, PIPE

p = Popen(['python', 'bot2.py'],stdout=PIPE, stdin=PIPE, close_fds=True)

flg = fcntl.fcntl(p.stdout.fileno(), fcntl.F_GETFL)
fcntl.fcntl(p.stdout.fileno(), fcntl.F_SETFL, flg | os.O_NONBLOCK)

for i in range(5):
    p.stdin.write('hello world {}\n'.format(i))
    p.stdin.flush()
    # sleep(2.0)
    ready = select([p.stdout.fileno()], [], [], 5.0)
    if len(ready) == 1:
        print 'msg from bot: {}'.format(os.read(p.stdout.fileno(), 100))
    else:
        print "The bot did not print anything"
os.kill(p.pid, signal.SIGTERM)

孩子的代码(bot2.py)

import os
import sys
from time import sleep
from select import select

sys.stdout = os.fdopen(sys.stdout.fileno(), 'w', 0)
while True:
    a = raw_input()
    print a
    sys.stdout.flush()

目标是在进程之间建立连接,以便它们可以交替地读写管道。我认为flush()没有做好这项工作。我尝试使用python -u将缓冲区大小设置为零。我做错什么了?你知道吗


Tags: fromimport管道osstdinstdoutsyssleep