0

I terminate my subprocess with p.terminate which I opened like this:

p = Popen([sys.executable, args], stdin=PIPE, stdout=PIPE, stderr=open("error.txt", 'a'))

As you can see I redirect all errors to a textfile so I can eaily read it. I missused this feature to print something into this file when the subprocess gets terminated:

signal.signal(signal.SIGTERM, sigterm_handler) # sets shutdown_flag
while True:
    if shutdown_flag:
        print("Some Useful information", file=sys.stderr)

However: The file is always empty. Is this because the pipe gets closed when terminate is called and whatever is written from the subprocess at this point is lost? Or is there any other issue I just dont see here?

Fuzzyma
  • 7,619
  • 6
  • 28
  • 60

1 Answers1

0

In general, it is not a good idea to terminate a thread. Rather, you should ask it to end using threading.Event.

event = threading.Event() 
while not event.isSet():   # use this instead of while True:
    #  do your stuff

# now write your file
print("Some Useful information", file=sys.stderr)

Then, instead of p.terminate(), use:

threading.Event().set()
Martin
  • 1,095
  • 9
  • 14
  • I am not using threads but subprocesses. Does it still work the same way? – Fuzzyma Nov 18 '16 at 12:53
  • My bad. I had threads on the brain. What you can do is similar. That is, tell the process to exit rather than killing it. I would recommend using p.communicate("please shut down") in place of p.terminate() Then, instead of waiting on the event in my original snippet, us data on stdin and look for "please shut down" (or whatever string you want). Also, and importantly, after p.communicate(), do a p.wait(). – Martin Nov 18 '16 at 13:44
  • thats not easily done in my case because I pipe data to the process. Setting up your solution would mix up data flow and control flow which I would like to keep seperated – Fuzzyma Nov 18 '16 at 14:12