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)

braheem38
  • 23
  • 5

1 Answers1

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
Jean-François Fabre
  • 137,073
  • 23
  • 153
  • 219