简体   繁体   中英

Cannot return value from `if __name__ == "__main__"` in a Python script?

I am trying to collect output of a Python script in a bash script where the Python script is called like below:

#!/bin/bash

outputString=$(./test.py 2>&1)
echo $outputString

But it looks like I cannot return from the block if __name__ == "__main__" ?

#!/usr/bin/env python

import sys

def my_method():
    return 'somethng'

if __name__ == "__main__":
    value = my_method()
    return value

Running test.sh complains the following error:

File "./test.py", line 11 return value SyntaxError: 'return' outside function

What am I doing wrong? I cannot return from inside if __name__ == "__main__" ?

You can obtain the exit value from python (or any other program) like this

#!/bin/bash

./test.py 2>&1
echo $?

you can exit with a value different than 0 if ther's an error

#!/usr/bin/env python

import sys

def my_method():
    return 'somethng'

if __name__ == "__main__":
    print(my_method())
    sys.exit(0)

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