I have a python script that both prints and returns some value. Like:
(pseudo code)
def main:
print "hello"
return 1
I'd like the shell script to capture the value returned (1) not the value printed (hello).
I have a python script that both prints and returns some value. Like:
(pseudo code)
def main:
print "hello"
return 1
I'd like the shell script to capture the value returned (1) not the value printed (hello).
Returning a value from that main()
function doesn't do anything here.
To return an exit code to the operating system (and thus a shell script), you should use sys.exit()
.
The script need to utilise sys.exit() in order to pass back some value to the caller. The value that can be return is limited to integers that can be expressed in 8 bits
For example we have foo.py implemented as:
import sys
print('All the world\'s a stage, And all the men and women merely players')
sys.exit(99)
Then, in another .py file we can have:
from subprocess import run
print(run(['python3', 'foo.py'], capture_output=True).returncode)
Output:
99