0

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)

Jonas
131k103 gold badges330 silver badges408 bronze badges
asked Dec 14, 2016 at 14:59
2
  • Could you specify how specifically it 'didn't work'? Please provide your output to aid in debugging. Commented Dec 14, 2016 at 15:04
  • I've edited my question Commented Dec 14, 2016 at 15:21

1 Answer 1

2

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
answered Dec 14, 2016 at 15:29
Sign up to request clarification or add additional context in comments.

2 Comments

It didn't help, the code still hangs on communicate(). The communicate call correctly sets done to true but the while loop in sniff() hangs after that
try to add a print statement in your while True loop, and after it too to see if it's reached.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.