2012-08-29 19 views
6

file di sp.py:?Come posso sapere se il mio sottoprocesso è in attesa per il mio ingresso (in python3)

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

file di 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 bloccherà nella prima pobj.stdout.read(), perché sp.py mi sta aspettando.
Ma se voglio elaborare la stringa 'In attesa di input:' per prima cosa, come posso sapere se sp.py mi sta aspettando?
In altre parole, desidero restituire pobj.stdout.read() quando sp.py è in attesa (o sta dormendo a causa di time.sleep()).

+0

Hai provato a usare 'pobj.communicate', come consigliato nel [doc sottoprocesso] (http://docs.python.org/library/ subprocess.html)? –

+0

Questa domanda potrebbe essere utile: http://stackoverflow.com/questions/375427/non-blocking-read-on-a-subprocess-pipe-in-python –

+0

@PierreGM Grazie mille. 'communicate' terminerà il sottoprocesso dopo essere stato chiamato. –

risposta

2

Ok, l'ho risolto. Il mio codice è basato su Non-blocking read on a subprocess.PIPE in python (Grazie, @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() 
Problemi correlati