I am trying to write a small app that uses the subprocess module.
My program calls an external Bash command that takes some time to process. During this time, I would like to show the user a series of messages like this:
Processing. Please wait…
The output is foo()
How can I do this using Popen.wait() or Popen.poll(). I have read that I need to use the Popen.returncode, but how I can get it to actively check the state, I don’t know.
Bothwait()(withtimeoutspecified) andpoll()returnNoneif the process has not yet finished, and something different if the process has finished (I think an integer, the exit code, hopefully 0).Edit:
wait()andpoll()have different behaviors:wait(without the timeout argument) will block and wait for the process to complete.waitwith the timeout argument will waittimeoutseconds for the process to complete. If it doesn’t complete, it will throw theTimeoutExpiredexception. If you catch the exception, you’re then welcome to go on, or towaitagain.pollalways returns immediately. It effectively does a wait with a timeout of 0, catches any exception, and returnsNoneif the process hasn’t completed.waitorpoll, if the process has completed, the popen object’sreturncodewill be set (otherwise it’s None – you can check for that as easily as callingwaitorpoll), and the return value from the function will also be the process’s return code.</Edit>
So I think you should do something like:
Be aware that if the bash script creates a lot of output you must use
communicate()or something similar to prevent stdout or stderr to become stuffed.