2012-08-29 9 views
6

plików sp.py:Skąd mogę wiedzieć, czy mój podproces czeka na mojego wejścia (w python3)

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

plik 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 zablokuje w najpierw pobj.stdout.read(), ponieważ czeka na mnie sp.py.
Ale jeśli chcę przetworzyć ciąg "Oczekiwanie na twoje dane wejściowe:" najpierw, skąd mogę wiedzieć, czy sp.py na mnie czeka?
Innymi słowy, chcę, aby pobj.stdout.read() powrócił, gdy sp.py czeka (lub śpi z powodu time.sleep()).

+0

próbowałeś użyć 'pobj.communicate', jak poinformowała w subprocess [doc] (http://docs.python.org/library/ subprocess.html)? –

+0

To pytanie może być pomocne: http://stackoverflow.com/questions/375427/nonblocking-read-on-a-subprocess-pipe-in-python –

+0

@PierreGM Wielkie dzięki. "komunikuj" zakończy podproces po wywołaniu. –

Odpowiedz

2

Dobra, udało mi się. Mój kod jest oparty na Non-blocking read on a subprocess.PIPE in python (dzięki, @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() 
Powiązane problemy