1

Hi folks I'm a scripting/python newbie but i have searched endlessly for a solution to no avail.

I am trying to call a sh script (using windows 10) using python (subprocess) and return the exit code to python.

For clarity i have stripped out everything except the relevant code.

I have an sh script 'return_value.sh' which literally has one line to set an exit code:

#!/bin/sh
exit 9

I can run this via git-bash and it returns exit_code 9 as expected.

When i try to call this from python however, it always returns zero:

import subprocess
p = subprocess.Popen(['C:\Program Files\Git\git-bash.exe','return_value.sh'], stdout=subprocess.PIPE)
p.wait()
out, err = p.communicate()
print (p.returncode)    

I've searched for ages and cannot find a resolution. The closest i could find was:

Why sometimes Python subprocess failed to get the correct exit code after running a process?

but it didnt help me. Can anyone please give me some advice?

Many thanks

Mike

7
  • 1
    Why shell=True if you are passing a list as the first argument? Commented Feb 6, 2018 at 17:18
  • 1
    Why shell=True ever? On UNIX, a shell will return the exit status of the last command it ran, but as a UNIX person, I have no idea of whether that's also true on Windows; if it's not, well, there's your problem. Commented Feb 6, 2018 at 17:32
  • 1
    Also note that the shell created with shell=True is not the shell you want to have invoked to execute your program; they're very different things. Commented Feb 6, 2018 at 17:34
  • This page describes cmd.exe %errorlevel% and how some commands will overwrite it, some will overwrite it on error only, and some will never modify it, and additionally that "In most cases the ERRORLEVEL will be the same as the exit code, but there are a few buggy cases where this fails.". So yeah, definitely try without the shell.... Commented Feb 6, 2018 at 18:11
  • subprocess shell=True uses the Windows %ComSpec% shell, which is almost always cmd.exe. If CMD can run "return_value.sh", it's via ShellExecuteEx using the registered "open" action for ".sh" files. That depends on your system configuration. Add some sleep or other delay in the script, and inspect the process tree in Process Explorer or pslist -t. If there are intermediate or orphaned processes, then CMD's exit code (from cmd.exe /c "return_value.sh") probably isn't from the process that actually executes the script. Commented Feb 7, 2018 at 0:14

0

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.