2012-08-29 47 views
6

tập tin sp.py:Làm thế nào tôi có thể biết liệu tiến trình con của tôi đang chờ đợi đầu vào của tôi (trong python3)

#!/usr/bin/env python3 
s = input('Waiting for your input:') 
print('Data:' + s) 

tập tin main.py

import subprocess as sp 
pobj = sp.Popen('sp.py',stdin=sp.PIPE,stdout=sp.PIPE,shell=True) 
print(pobj.stdout.read().decode()) 
pobj.stdin.write(b'something...') 
print(pobj.stdout.read().decode()) 

main.py sẽ chặn trong đầu tiên pobj.stdout.read(), bởi vì sp.py đang chờ tôi.
Nhưng nếu tôi muốn xử lý chuỗi 'Đang chờ bạn nhập:' trước tiên, làm cách nào để biết liệu sp.py có đang đợi tôi không?
Nói cách khác, tôi muốn pobj.stdout.read() trả lại khi sp.py đang chờ (hoặc ngủ vì time.sleep()).

+0

Các bạn đã cố gắng sử dụng 'pobj.communicate', như khuyến cáo trong [subprocess doc] (http://docs.python.org/library/ subprocess.html)? –

+0

Câu hỏi này có thể hữu ích: http://stackoverflow.com/questions/375427/non-blocking-read-on-a-subprocess-pipe-in-python –

+0

@PierreGM Cảm ơn rất nhiều. 'communication' sẽ chấm dứt tiến trình con sau khi được gọi. –

Trả lời

2

OK, tôi đã làm việc đó. Mã của tôi được dựa trên Non-blocking read on a subprocess.PIPE in python (Cảm ơn, @VaughnCato)

#!/usr/bin/env python3 
import subprocess as sp 
from threading import Thread 
from queue import Queue,Empty 
import time 

def getabit(o,q): 
    for c in iter(lambda:o.read(1),b''): 
     q.put(c) 
    o.close() 

def getdata(q): 
    r = b'' 
    while True: 
     try: 
      c = q.get(False) 
     except Empty: 
      break 
     else: 
      r += c 
    return r 

pobj = sp.Popen('sp.py',stdin=sp.PIPE,stdout=sp.PIPE,shell=True) 
q = Queue() 
t = Thread(target=getabit,args=(pobj.stdout,q)) 
t.daemon = True 
t.start() 

while True: 
    print('Sleep for 1 second...') 
    time.sleep(1)#to ensure that the data will be processed completely 
    print('Data received:' + getdata(q).decode()) 
    if not t.isAlive(): 
     break 
    in_dat = input('Your data to input:') 
    pobj.stdin.write(bytes(in_dat,'utf-8')) 
    pobj.stdin.write(b'\n') 
    pobj.stdin.flush() 
Các vấn đề liên quan