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.