我认为您可能只是没有看到正在发生的事情的输出。这是一个似乎适用于我的盒子的完整示例,除非我完全误解了你想要的东西。我所做的主要更改是将stdout 的p 设置为sys.stdout 而不是subprocess.PIPE。也许我误解了你的问题的主旨,那一点很关键......
这是完整的代码和输出:
在发送(测试)过程中(我将其命名为 test_comms.py)。我目前在 Windows 上,所以请原谅.bat:
import time
import subprocess
import sys
# Note I'm sending stdout to sys.stdout for observation purposes
p = subprocess.Popen(args = 'myapp.bat',
stdin = subprocess.PIPE,
stdout = sys.stdout,
universal_newlines=True)
#Send 10 messages to the process's stdin, 1 second apart
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 包含(使用 Queue 而不是 queue - 当前环境 Python 2):
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")
# Read off the queue - note it's being filled asynchronously based on
# When it receives messages. I set the read interval below to 2 seconds
# to illustrate the queue filling and emptying.
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