The Python Oracle

How to determine subprocess.Popen() failed when shell=True

--------------------------------------------------
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------

Music by Eric Matyas
https://www.soundimage.org
Track title: Luau

--

Chapters
00:00 How To Determine Subprocess.Popen() Failed When Shell=True
00:45 Answer 1 Score 5
01:14 Accepted Answer Score 16
01:27 Thank you

--

Full question
https://stackoverflow.com/questions/2861...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #subprocess #popen

#avk47



ACCEPTED ANSWER

Score 16


returncode will work, although it will be None until you've called p.poll(). poll() itself will return the error code, so you can just do

if a.poll() != 0:
    print ":("



ANSWER 2

Score 5


In the first case it fails to start, in the second - it successfully starts shell which, in turn, fails to execute the application. So your process has been properly spawned, exited and waits for you to inquire about its exit code. So, the thing is, unless your shell or environment (e.g. no memory) is utterly broken there's no way Popen itself may fail.

So, you can safely .poll() and .wait() on it to get all the sad news.