Python subprocess自定义返回码问题:无法获取预期错误返回码
Let's break down why you're getting a return code of 0 instead of the expected 2, and how to fix it quickly.
The Root Problem
Your test.py script calls main() and gets a return value of 2, but Python doesn't automatically use that return value as the script's exit code. By default, Python scripts exit with code 0 unless you explicitly tell it otherwise. The return statement in your main() function just passes a value back to the caller (the if __name__ == '__main__': block), but that block doesn't do anything with it—so the script exits with the default 0.
The Fix: Explicitly Set the Exit Code
You need to import the sys module and use sys.exit() to pass the main() return value as the script's exit code. Here's the updated test.py:
import sys RETCODE_OK = 0 RETCODE_THING_1_FAILED = 1 RETCODE_THING_2_FAILED = 2 def main(): return RETCODE_THING_2_FAILED if __name__ == '__main__': sys.exit(main())
Verify the Fix
Now when you run your subprocess code, you'll get the expected return code:
import subprocess proc = subprocess.Popen('python test.py', shell=True) proc.communicate() print(proc.returncode) # Outputs 2, as desired
A Safer Alternative to shell=True
Using shell=True can introduce security risks (like shell injection) if your command includes untrusted input. A better practice is to pass the command as a list of arguments:
proc = subprocess.Popen(['python', 'test.py'])
This works the same way but avoids unnecessary shell overhead and security pitfalls.
Key Takeaways
- Python scripts don't use function return values as exit codes by default—you need
sys.exit()for that. - Always make sure your script explicitly sets its exit code if you're relying on it for subprocess error handling.
- Prefer list-based command arguments over
shell=Truefor safer, more predictable behavior.
内容的提问来源于stack exchange,提问作者Ben Caine

