我想你可能没有看到正在进行的操作的输出。以下是一个完整的示例,它似乎在我的计算机上可以运行,除非我完全误解了您想要的内容。我所做的主要更改是将p
的stdout
设置为sys.stdout
,而不是subprocess.PIPE
。也许我误解了您问题的重点,那一部分至关重要...
以下是完整代码和输出:
在发送过程(测试)中(我将其命名为test_comms.py)。我当前正在使用Windows,因此需要使用.bat
文件:
import time
import subprocess
import sys
p = subprocess.Popen(args = 'myapp.bat',
stdin = subprocess.PIPE,
stdout = sys.stdout,
universal_newlines=True)
for i in range(10):
time.sleep(1)
p.stdin.write('my message\n')
myapp.bat是一个非常简单的脚本:
echo "In the bat cave (script)"
python myapp.py
我的应用程序myapp.py包含以下内容(在当前环境Python 2中使用Queue
而不是queue
):
import Queue
from Queue import Empty
import threading
import sys
import time
def get_input():
print("Started the listening thread")
for line in iter(sys.stdin.readline, ''):
print("line arrived to put on the queue\n")
q.put(line)
sys.stdin.close()
print("Hi, I'm here via popen")
q = Queue.Queue()
threading.Thread(name = 'input-getter',
target = get_input).start()
print("stdin listener Thread created and started")
while True:
time.sleep(2)
try:
print('Queue size is',q.qsize())
print('input:', q.get_nowait())
except Empty:
print('no input')
print("Past my end of code...")
输出:
D:\>comms_test.py
D:\>echo "In the bat cave (script)"
"In the bat cave (script)"
D:\>python myapp.py
Hi, I'm here via popen
Started the listening threadstdin listener Thread created and started
line arrived to put on the queue
line arrived to put on the queue
('Queue size is', 2)
('input:', 'my message\n')
line arrived to put on the queue
line arrived to put on the queue
('Queue size is', 3)
('input:', 'my message\n')
line arrived to put on the queue
line arrived to put on the queue
('Queue size is', 4)
('input:', 'my message\n')
line arrived to put on the queue
line arrived to put on the queue
('Queue size is', 5)
('input:', 'my message\n')
line arrived to put on the queue
line arrived to put on the queue
D:\>('Queue size is', 6)
('input:', 'my message\n')
('Queue size is', 5)
('input:', 'my message\n')
('Queue size is', 4)
('input:', 'my message\n')
('Queue size is', 3)
('input:', 'my message\n')
('Queue size is', 2)
('input:', 'my message\n')
('Queue size is', 1)
('input:', 'my message\n')
('Queue size is', 0)
no input
('Queue size is', 0)
no input
('Queue size is', 0)
no input
communicate
(它只发送数据,然后等待进程终止);而是直接写入p.stdin
。 - pokestdin.flush()
?使用像async_subprocess这样的模块如何? - Inbar Rosefor line in sys.stdin: got(line)
(注意:你不需要iter(...)
,这里没有预读错误)-它逐行读取直到EOF,必要时等待每行。我理解“非阻塞”q.get_nowait()
会立即返回一行或引发“Empty”异常。但是,“非阻塞连续”在一起的行为是什么?如果你将q.get_nowait()
放在一个循环中,如果出现“Empty”异常,你想做什么(如果答案是什么都不做... - jfs