How to get return type from Python script

272 Views Asked by At

I have the following code saved as some_file.py:

def some_function(num):
    return int(num) + 1


if __name__ == "__main__":
    val = some_function(sys.argv[1])

When I run the script like:

some_file.py 10

I want to catch the return value. I tried this approach, unsuccessfully:

if __name__ == "__main__":
        val = some_function(sys.argv[1])
        sys.exit(val)
1

There are 1 best solutions below

4
On

The exit code is put in $?

python some_file.py 10
echo $?

will print 11

Exit codes are a limited mechanism, it only allows values from 0 to 255. Usually it's more appropriate to capture the output.

if __name__ == "__main__":
    val = some_function(sys.argv[1])
    print(val)

then you can use

somevariable=$(python some_file.py 10)
echo "$somevariable"