2012-08-29 78 views
6

文件sp.py:我怎樣才能知道我是否子進程正在等待我的輸入(在python3)

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

文件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將在阻止第一個pobj.stdout.read(),因爲sp.py正在等待我。
但是,如果我想處理字符串'等待輸入:'首先,我怎麼知道sp.py是否在等我?
換句話說,我希望pobj.stdout.read()在sp.py等待時(或因爲time.sleep()而睡覺)返回。

+0

你有沒有試過用'pobj.communicate',如[子DOC]建議(http://docs.python.org/library/ subprocess.html)? –

+0

這個問題可能會有所幫助:http://stackoverflow.com/questions/375427/non-blocking-read-on-a-subprocess-pipe-in​​-python –

+0

@PierreGM非常感謝。 「溝通」將在被調用後終止子進程。 –

回答

2

好吧,我已經完成了。我的代碼是基於Non-blocking read on a subprocess.PIPE in python(謝謝,@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()