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.