I'm working with/rewriting a code that first defines a function as follows:
def main(argv=[__name__]):
...
*rest of code*
...
and ends with:
if __name__ == "__main__":
sys.exit(main(sys.argv))
I'm under the impression that what this is doing is checking to make sure that the script is being executed from the command line, and then running the function main
with the arguments provided as it exits python. But then, why is it necessary to preset the variable argv
to [__name__]
in the function definition? This is not my code, so I don't know the original intention behind this. I am, however, new to using if __name__ == "__main__":
lines to spot check command line execution, so maybe there is some glaringly obvious reason for this syntax that I'm missing. Any help, or further detail on main
function definition and argument/command-line-vs-module testing would be appreciated.
The
main()
definition allows for the possibility thatmain()
will be called in other ways than thesys.exit()
line at the bottom of the file. This might be an example of defensive programming, or it might indicate other supported uses of this file.One such other supported use might be to invoke it from another Python program, like so: