Jan-03-2019, 05:24 PM
(This post was last modified: Jan-03-2019, 05:25 PM by Gribouillis.)
There is an old code that I used in Linux for certain cases when stdout blocks with subprocess. It uses socketpair() and select(). Here is an example involving two scripts a.py and b.py (launched by a.py which reads its output), but it also works when the second process is not a python program. I already posted this in other forums but I think it's a nice trick to know
################################## # a.py import subprocess import socket import select esock, echildsock = socket.socketpair() osock, ochildsock = socket.socketpair() p = subprocess.Popen(['python3','b.py'], stderr=echildsock.fileno(), stdout=ochildsock.fileno()) while p.poll() is None: r, w, x = select.select([esock, osock],[],[], 1.0) if not r: continue # timed out for s in r: print('stdout ready' if s is osock else 'stderr ready') data = s.recv(1024) print('received', data.decode('utf8')) osock.shutdown(socket.SHUT_RDWR) osock.close() esock.shutdown(socket.SHUT_RDWR) esock.close()
################################## # b.py res = input('???') print('in b:', res)