-1

I have a simple Python code:

import sys

def main(argv1, argv2):
    return 0 

if __name__ == '__main__':
    return main()

Basically I want the code to return to caller what main functions returns but I get the below error during execution:

$ python ../myexamples/sample.py
  File "../myexamples/sample.py", line 11
    return main()
    ^
SyntaxError: 'return' outside function

Is it that main method cannot return any value back to OS?

Programmer
  • 8,303
  • 23
  • 78
  • 162
  • 2
    there is no main function in python. `if __name__ == '__main__':` is not a function. So `return main()` makes no sense. – Paritosh Singh Aug 07 '19 at 06:46
  • 4
    What's the caller? Are you trying to set the program's exit code? You might want `sys.exit(1)` to indicate error. The default exit from main is 0, so you don't need to do anything other than let the Python program end normally to have the same effect as `return 0;` in C. – ggorlen Aug 07 '19 at 06:46
  • The Python code will be called by Unix script – Programmer Aug 07 '19 at 06:47
  • @ParitoshSingh So how can we return an value back to caller - just like the way a C program does? – Programmer Aug 07 '19 at 06:48
  • Maybe you want to check out https://stackoverflow.com/questions/8567526/calling-a-python-function-from-a-shell-script – PeptideWitch Aug 07 '19 at 06:50
  • 2
    See my above comment. In C, you write: `int main() { return 0; }`. To get the same result in Python, you write nothing. Python does all this boilerplate implicitly. Can you post exactly what you're trying to accomplish here? What is the parent script that's waiting on the exit code? – ggorlen Aug 07 '19 at 06:52
  • yep, ggorlen pretty much answered it. Remember, at the end of the day, this is python, not C. All C conventions will not carry over 1:1. – Paritosh Singh Aug 07 '19 at 07:05

2 Answers2

0

If the objective if to get the exit code back to the os at the end of the program execution it is possible using the exit function, the return statement can only be used inside function but a python program itself is not a function. So to answer your question you can do something like this

import sys

def main(argv1, argv2):
    return 0 

if __name__ == '__main__':
    exit_code = main()
    exit(exit_code)

Xiidref
  • 1,456
  • 8
  • 20
0

"return" is only valid in function, so the valid code should be:

import sys

def main(argv1, argv2):
    return 0 

if __name__ == '__main__':
    main()

And if you want get the return value of this function, the valid code should be:

import sys

def main(argv1, argv2):
    return 0 

if __name__ == '__main__':
    return_value = main()
Rt.Tong
  • 196
  • 3
  • 5