Many Python modules are also intended to be callable as standalonescripts. This PEP proposes that a special function called__main__()should serve this purpose.
There should be one simple and universal idiom for invoking a moduleas a standalone script.
The semi-standard idiom:
if__name__=='__main__':perform"standalone"functionality
is unclear to programmers of languages like C and C++. It also doesnot permit invocation of the standalone function when the module isimported. The variant:
if__name__=='__main__':main_function()
is sometimes seen, but there exists no standard name for the function,and because arguments are taken from sys.argv it is not possible topass specific arguments without changing the argument list seen by allother modules. (Imagine a threaded Python program, with two threadswishing to invoke the standalone functionality of different moduleswith different argument lists)
The standard name of the ‘main function’ should be__main__. When amodule is invoked on the command line, such as:
pythonmymodule.py
then the module behaves as though the following lines existed at theend of the module (except that the attribute __sys may not be used orassumed to exist elsewhere in the script):
ifglobals().has_key("__main__"):importsysas__sys__sys.exit(__main__(__sys.argv))
Other modules may execute:
importmymodulemymodule.__main__(['mymodule',...])
It is up tomymodule to document thread-safety issues or otherissues which might restrict use of__main__. (Other issues mightinclude use of mutually exclusive GUI modules, non-sharable resourceslike hardware devices, reassignment ofsys.stdin/stdout, etc)
Inmodules/main.c, the block near line 385 (after thePyRun_AnyFileExFlags call) will be changed so that the above code(or its C equivalent) is executed.
__main__ be treated as the exit value?Yes. Many__main__ will naturally returnNone, whichsys.exit translates into a “success” return code. In those thatreturn a numeric result, it behaves just like the argument tosys.exit() or the return value from C’s main().
__main__ includeargv[0], or just the“real” argumentsargv[1:]?argv[0] is included for symmetry withsys.argv and easytransition to the new standard idiom.
In a short discussion on python-dev[1], two major backwardscompatibility problems were brought up and Guido pronounced that hedoesn’t like the idea anyway as it’s “not worth the change (in docs,user habits, etc.) and there’s nothing particularly broken.”
This document has been placed in the public domain.
Source:https://github.com/python/peps/blob/main/peps/pep-0299.rst
Last modified:2025-02-01 08:59:27 GMT