How can I find out if my subprocess is waiting for my input? (In python3)

sp.py file:

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

file 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 will be blocked in the first pobj.stdout.read() , because sp.py is waiting for me.
But if I want to process the line "Waiting for input": first, how can I find out if sp.py is waiting for me?
In other words, I want pobj.stdout.read() return when sp.py was waiting (or sleeping because of time.sleep() ).

+6
source share
1 answer

Ok, I did it. My code is based on non-blocking reading on the .PIPE subprocess in python (Thanks, @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() 
+2
source

Source: https://habr.com/ru/post/924086/


All Articles