I execute the following code in both windows cmd and ubuntu bash:
python -c "import xxx"
Error messages output. And when I run:
echo $? / echo %errorlevel%
The value is 1.
When I do the same task in python script with subprocess as follows:
cmdlst = ['python', '-c', '"import xxx"‘]
proc = subprocess.Popen(cmdlst)
retcode = proc.wait()
The retcode is 0. What is the problem and how can I get the correct return code of the command run within a subprocess.
Thanks in advance.
1 Answer 1
Running the shell command (equivalent to your given subprocess.Popen() call if we disregard the use of "smart quotes")
'python' '-c' '"import xxx"'
correctly exits with status 0, whether or not a module named xxx exists.
This is because "import xxx" is a string, and evaluating a string does not throw an exception. You'd get the exact same behavior from python -c '"hello world"', or any other string.
If you really want to try executing the code import xxx, then you need to remove the extra quotes:
subprocess.Popen(['python', '-c', 'import xxx']).wait()
...will properly return 1 (if no xxx module exists).
'"import xxx"‘is a very different thing from'"import xxx"', and the former -- which is what is included in the question -- wouldn't exit with status 0).