Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get correct exitcode in when running python script from another Script?

I have a file one.py

import sys
sys.exit(-23)

when I'm calling it from another file using both

ans = subprocess.call("python c:\python27\one.py")
                  or 
ans = os.system("python c:\python27\one.py")

it returns me value "2" and I want value as -23.

How do we do it ?

EDIT: Somebody marked this as possible duplicate of Another question .. which is a bash script but actually this question is related to python and it's calls where how exitcodes work.. how to run another python script has many answers but no one has discussed exit codes in that one .. infact i searched properly that one before asking question

like image 453
niyant Avatar asked Feb 15 '26 09:02

niyant


1 Answers

you have 2 problems

1) you use negative exit codes, and they are not always possible. you might get 233 as exit code (the exit code is treated as a unsigned byte so it can be between 0 - 255)

2) you get an error when you run this because you try to run it in a shell form , you can make this work with

ans = subprocess.call(['python',r"c:\python27\one.py"]) # This r before addr. is important.. else you will still get the same value

or the less recommended way shell=True argument like this

ans = subprocess.call(r"python c:\python27\one.py", shell=True)

but that is not recommended because of security issues (if the user input can affect your command)

like image 64
DorElias Avatar answered Feb 16 '26 21:02

DorElias