On Fri, May 29, 2020 at 12:43 PM Jonathan Goble firstname.lastname@example.org wrote:
On Thu, May 28, 2020 at 9:03 PM Greg Ewing email@example.com wrote:
On 29/05/20 8:05 am, firstname.lastname@example.org wrote:
People write main entry points that are not exactly this?
If __name__ == '__main__': sys.exit(main(sys.argv[1:]))
It's not clear that exiting with the return value of main() is the most Pythonic thing to do -- it's more of a C idiom that doesn't seem so useful when exceptions exist.
If all you care about in terms of exit codes is 0 for success and 1 for error (which is sufficient for most scripts), then yes, this is probably not needed.
However, it's useful in two cases. One is if you're writing a script tool to be distributed, where you probably want to have a blanket "except Exception" clause in main() to catch everything and print a graceful failure message. In that case, you probably want to suppress the ugly traceback, which requires manually producing the appropriate exit code (probably 1, but maybe something else).
But thanks to exception handling, we can unwind the stack in a perfectly clean manner AND specify a return value, all in one simple operation:
You don't need to carry the return value from main. You don't have to worry about how deep into your call stack the decision to exit is. You just sys.exit with whatever value you want, and everything will be cleaned up perfectly.
So the logic can simply be: If main returns, then it was successful, and we exit zero. If main raises an exception, then it was unsuccessful, and we exit one, or some other value if specified by the exception. And that's spelled:
if __name__ == '__main__': main()