I know that this is a frequently asked question and I've tried any solution approach which I could find here and on other sites^but couldn't solve my problem. My dilemma looks as follows (on Windows):
I have a main script (main.py) where I am creating a subprocess via Popen calling another script (sniffer.py) . Afterwards I am doing some stuff in main.py and finally want to send a character to the subprocess to finish the endless loop in sniffer.py and finally the whole subprocess.
main.py
process = Popen(["python", "sniffer.py", receiverIP, senderIP, "udp", path],stdin=PIPE)
#do some stuff
process.communicate('terminate')
sniffer.py
def check(done):
while True:
if sys.stdin.read() == 'terminate':
done = True
break
def sniff(someparams):
done = False
input_thread = threading.Thread(target=check, args=(done,))
input_thread.daemon = True
input_thread.start()
while True:
#do some stuff
if done:
break
I've also tried to combine the communicate call with a stdin.write, but it had no effect.
Note: I've noticed that, the while loop in sniffer.py doesn't continue after my communicate() call (the whole script just hangs)
-
Could you specify how specifically it 'didn't work'? Please provide your output to aid in debugging.awerchniak– awerchniak2016年12月14日 15:04:57 +00:00Commented Dec 14, 2016 at 15:04
-
I've edited my questionbraheem38– braheem382016年12月14日 15:21:41 +00:00Commented Dec 14, 2016 at 15:21
1 Answer 1
Nothing to do with subprocess.
You change done to True locally. You have to define it globally for the last loop to exit properly.
done = False
def check():
global done
while True:
if sys.stdin.read() == 'terminate':
done = True
break
def sniff(someparams):
global done
done = False
input_thread = threading.Thread(target=check)
input_thread.daemon = True
input_thread.start()
while True:
#do some stuff
if done:
break
2 Comments
while True loop, and after it too to see if it's reached.