BDFL published an article in 2003 on how to write a basic Python function . His example is this:
import sys
import getopt
class Usage(Exception):
def __init__(self, msg):
self.msg = msg
def main(argv=None):
if argv is None:
argv = sys.argv
try:
try:
opts, args = getopt.getopt(argv[1:], "h", ["help"])
except getopt.error, msg:
raise Usage(msg)
except Usage, err:
print >>sys.stderr, err.msg
print >>sys.stderr, "for help use --help"
return 2
if __name__ == "__main__":
sys.exit(main())
The reason for the optional argument argvto main()is: "We are changing main()to take an optional argument argvthat allows us to call it from an interactive Python prompt."
He explains the last line of his code as follows:
Now the challenges are sys.exit()annoying: when main()called sys.exit(), your interactive Python interpreter will exit! The tool is permission. The main()return value indicates the exit status. Thus, the code at the very end becomes
if __name__ == "__main__":
sys.exit(main())
sys.exit(n) main() return n.
, Guido Spyder, . ? import, main(), execfile runfile? , , , , , , import foo reload(foo).
, SystemExit getopt , , Python , , BDFL.