Python main() functions by Guido van van Rossum
2012-12-12 15:41
169 查看
http://www.artima.com/weblogs/viewpost.jsp?thread=4829
All Things Pythonic
Python main() functions
by Guido van van Rossum
May 15, 2003
Summary
For Python programmers, I've got some suggestions on how to write a main() function that's easy to invoke in other contexts, e.g. from the interactive Python prompt when you feel like experimenting.
I've written a few main() functions in my time. They usually have astructure roughly like this:
I'm sure many people write similar main() functions. I've got a fewsuggestions that make main() a little more flexible, especially asoption parsing becomes more complex.
First, we change main() to take an optional 'argv' argument, whichallows us to call it from the interactive Python prompt:
Note that we fill in the default for argv dynamically. This is moreflexible than writing
because sys.argv might have been changed by the time the call is made;the default argument is calculated at the time the main() function isdefined, for all times.
Now the
and the calls to sys.exit(n) inside main() all become
Another refinement is to define a Usage() exception, which we catchin an except clause at the end of main():
This gives the main() function a single exit point, which ispreferable over multiple
You might think that taking this to the extreme would move thetry/except clause out of the main() function, into the code at the endof the module (
get atraceback for command line syntax errors, which isn't very helpful.
However, another generalization can be helpful: defineanother exception, perhaps called
very friendly.
What's your favorite convention for writing main()?
his weblog, subscribe to his
RSS feed.
Digg
|
del.icio.us
|
Reddit
This weblog entry is Copyright © 2003 Guido van van Rossum. All rights reserved.
呵呵,关于正文后面段落的部分倒不是很理解
All Things Pythonic
Python main() functions
by Guido van van Rossum
May 15, 2003
Summary
For Python programmers, I've got some suggestions on how to write a main() function that's easy to invoke in other contexts, e.g. from the interactive Python prompt when you feel like experimenting.
I've written a few main() functions in my time. They usually have astructure roughly like this:
"""Module docstring. This serves as a long usage message. """ import sys import getopt def main(): # parse command line options try: opts, args = getopt.getopt(sys.argv[1:], "h", ["help"]) except getopt.error, msg: print msg print "for help use --help" sys.exit(2) # process options for o, a in opts: if o in ("-h", "--help"): print __doc__ sys.exit(0) # process arguments for arg in args: process(arg) # process() is defined elsewhere if __name__ == "__main__": main()
I'm sure many people write similar main() functions. I've got a fewsuggestions that make main() a little more flexible, especially asoption parsing becomes more complex.
First, we change main() to take an optional 'argv' argument, whichallows us to call it from the interactive Python prompt:
def main(argv=None): if argv is None: argv = sys.argv # etc., replacing sys.argv with argv in the getopt() call.
Note that we fill in the default for argv dynamically. This is moreflexible than writing
def main(argv=sys.argv): # etc.
because sys.argv might have been changed by the time the call is made;the default argument is calculated at the time the main() function isdefined, for all times.
Now the
sys.exit()calls are annoying: when main()calls
sys.exit(), your interactive Python interpreterwill exit! The remedy is to let main()'s return value specify the exitstatus. Thus, the code at the very end becomes
if __name__ == "__main__": sys.exit(main())
and the calls to sys.exit(n) inside main() all become
return n.
Another refinement is to define a Usage() exception, which we catchin an except clause at the end of main():
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)
# more code, unchanged
except Usage, err:
print >>sys.stderr, err.msg
print >>sys.stderr, "for help use --help"
return 2
if __name__ == "__main__": sys.exit(main())
This gives the main() function a single exit point, which ispreferable over multiple
return 2statements. This alsomakes it easier to refactor the argument parsing:
raiseUsageworks just fine from inside a helper function, but
return 2would require careful passing on of the returnvalues.
You might think that taking this to the extreme would move thetry/except clause out of the main() function, into the code at the endof the module (
if __name__ == "__main__": .... But thatwould mean that when you call main() interactively, you'd
get atraceback for command line syntax errors, which isn't very helpful.
However, another generalization can be helpful: defineanother exception, perhaps called
Error, which is treatedjust like
Usagebut returns 1. This can then be used forexpected errors like failure to open necessary files, which are notcommand line syntax errors, but yet expected, and where again atraceback doesn't feel
very friendly.
What's your favorite convention for writing main()?
Talk Back!
Have an opinion?Readers have already posted29commentsabout this weblog entry. Why notadd yours?RSS Feed
If you'd like to be notified whenever Guido van van Rossum adds a new entry tohis weblog, subscribe to his
RSS feed.
Digg
|
del.icio.us
|
About the Blogger
Guido van Rossum is the creator of Python, one of the majorprogramming languages on and off the web. The Python community refers to him as the BDFL (Benevolent Dictator For Life), a title straightfrom a Monty Python skit. He moved from the Netherlands to the USA in1995, where he met his wife. Until July 2003 they lived in thenorthern Virginia suburbs of Washington, DC with their son Orlijn, whowas born in 2001. They then moved to Silicon Valley where Guido now works for Google(spending 50% of his time on Python!). |
呵呵,关于正文后面段落的部分倒不是很理解
相关文章推荐
- [转载]Web Frameworks for Python by Guido van Rossum
- Python语言作者Guido van Rossum讲述Python 3的演变
- Python队列服务 Python RQ Functions from the __main__ module cannot be processed by workers.
- [转载]Django vs. Cheetah: 1-0 by Guido van Rossum
- [Python] First-class Everything (Python缔造者Guido van Rossum关于bound/unbound method的来历叙述)
- Python之父Guido van Rossum专题访谈
- 纯YY一下,在The Python Tutorial中,从Guido van Rossum的例子中可以看出他对现在流行的脚本语言perl,tcl,ruby,lua,python的评分
- [Python] 当猎头遇上 Guido van Rossum
- Python队列服务 Python RQ Functions from the __main__ module cannot be processed by workers.
- CSDN推荐技术专家:Guido van Rossum先生简介
- Guido van Rossum致中国读者信
- "There is only one way to do it, the right way” -------Guido van Rossum
- Guido van Rossum致中国读者信
- Guido von Rossum - i wrote python
- python中if __name__ == '__main__': 的解析
- python,build in functions
- CLR Assembly RegEx Functions for SQL Server by Example
- Python 解析ini文件 By ConfigParser
- Mac OSX 正確地同時安裝 Python 2.7 和 Python3 By Candy Tsai In Come on~ Python 11-29-2015 2 Min read 8 comme
- Python中if __name__='__main__':的解析