0

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.

2
  • Huh? The "smart quotes" you're using here aren't valid syntax at all. Commented Jul 18, 2017 at 2:37
  • (that is to say, '“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). Commented Jul 18, 2017 at 14:53

1 Answer 1

2

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).

Sign up to request clarification or add additional context in comments.

1 Comment

I've got it. Thanks

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.