1

How can I return a process id of a lengthy process started using Thread in Python before the thread completes its execution?

  1. I'm using Tkinter GUI so I can't start a lengthy process on the main thread so instead I start one on a separate thread.
  2. The thread in turn calls subprocess.popen. This process should run for like 5 -6 hours.
  3. But When I press stopbutton I need this process to stop but I am unable to return the process id of the process created using subprocess.popen.

Is there any solution to this?

lennon310
  • 12,503
  • 11
  • 43
  • 61
shibu s
  • 41
  • 2
  • Save the `pid` in `global var` so you are able to `signal` the `process` to terminate. – stovfl Mar 31 '17 at 16:08
  • Possible duplicate of [Opening a process with Popen and getting the PID](https://stackoverflow.com/questions/7989922/opening-a-process-with-popen-and-getting-the-pid) – ti7 Jun 06 '17 at 02:51

1 Answers1

0

If you are using subprocess.Popen simply to spin off another process, there is no reason you need to do so from another thread. A sub-process created this way does not block your main thread. You can continue to do other things while the sub-process is running. You simply keep a reference to the Popen object returned.

The Popen object has all the facilities you need for monitoring / interacting with the sub-process. You can read and write to its standard input and output (via stdin and stdout members, if created with PIPE); you can monitor readability / writability of stdin and stdout (with select module); you can check whether the sub-process is still in existence with poll, reap its exit status with wait; you can stop it with terminate (or kill depending on how emphatic you wish to be).

There are certainly times when it might be advantageous to do this from another thread -- for example, if you need significant interaction with the sub-process and implementing that in the main thread would over-complicate your logic. In that case, it would be best to arrange a mechanism whereby you signal to your other "monitoring" thread that it's time to shutdown and allow the monitoring thread to execute terminate or kill on the sub-process.

Gil Hamilton
  • 11,973
  • 28
  • 51