(Mar-04-2018, 06:24 AM)Gribouillis Wrote: The return value of the main function is not the same thing as the program's exit status (because main() is not special) unless you call sys.exit(main())
as wavic does. The program should exit with value 0 to indicate success.
I need to ask everyone to forgive my ignorance, but I'm not quite understanding exactly how these programs are run.
My IDE creates the following template automatically when I start a new python project.
def main(args):
return 0
if __name__ == '__main__':
main()
Now this is going to really sound stupid, but my question is, "What the heck is this thing?"
Is this a class? If so does it have a name? Obviously it's a file and it has a file name. So what is the file name? The name of the program? The name of the class? The name of a module?
I'm not clear on the difference between these things.
I've learned that I can change the name of the main method as long as I change it both in the method definition as well as in the if statement at the bottom like so:
None the less it appears that Python is looking for something named
'__main__'
in order to run at all.
def my_method():
return 0
if __name__ == '__main__':
my_method()
Now in terms of what wavic is doing I have some questions:
Here's wavic's original code
def main():
return 0 # it's not necessary but you can do it
if __name__ == '__main__':
import sys
sys.exit(main())
If I were to modify this code as follows it should run just fine, right?
def my_method():
return 0 # it's not necessary but you can do it
if __name__ == '__main__':
import sys
sys.exit(my_method())
However if I were to modify this code as follows it should never run at all, right?
def main():
return 0 # it's not necessary but you can do it
if __name__ == '__main__':
import sys
sys.exit()
I'm guessing that sys.exit() will only exit after it has run whatever is placed inside the brackets?
In other words
sys.exit(method_x())
will first run
method_x()
and then exit the program. Is this correct?
And if so, how does
sys.exit(method_x())
know when
method_x()
is finished running if
method_x()
doesn't have a
return
?
Sorry for the confusion here, but I'm trying to understand exactly what's going on.