0

I am triggering a shell script using a Python script and get its exit code for further processing. I am using the subprocess module. But when I try to capture the return code for further processing it is always 0 even if the script failed.

Below is my Python code:

import subprocess
import os
    
    
dpath = "/home/admin/temp"
password = "password"
password_bytes = bytes(password + '\n', encoding='utf-8')
proc = subprocess.Popen(['sudo', '-S', 'sh', os.path.join(dpath,'test1.sh'),'hello'], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
out, err = proc.communicate(input=password_bytes)
    
print(proc.returncode)
print(out)
if proc.returncode == 0:
    print("success")
else:
    print("fail")

Below is my shell script

cat file.txt #File.txt does not exist
echo $?

Below is my python output

0
b'1\n'
success

You can see print(out) gives exit code 1 but proc.returncode gives 0.

0

1 Answer 1

1

The return code is 0 because you have added an echo statement, which does not fail. Try simply having cat file where file does not exist, without the echo statement.

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

1 Comment

To point out explicitly why that is, the exit code of a script is the exit code of the last command in the script; so, here, echo.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.