简体   繁体   中英

How to get return type from Python script

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)

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"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM