On Fri, May 29, 2020 at 12:43 PM Jonathan Goble <jcgob...@gmail.com> wrote:
>
> On Thu, May 28, 2020 at 9:03 PM Greg Ewing <greg.ew...@canterbury.ac.nz> 
> wrote:
>>
>> On 29/05/20 8:05 am, tritium-l...@sdamon.com 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:

sys.exit(4)

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()

ChrisA
_______________________________________________
Python-ideas mailing list -- python-ideas@python.org
To unsubscribe send an email to python-ideas-le...@python.org
https://mail.python.org/mailman3/lists/python-ideas.python.org/
Message archived at 
https://mail.python.org/archives/list/python-ideas@python.org/message/HSH4WCZ5UT7QYYDBBYGRLNQHUGUUKVXE/
Code of Conduct: http://python.org/psf/codeofconduct/

Reply via email to