argparse python 模块行为的解释:大写占位符从哪里来? [英] Explanation for argparse python modul behaviour: Where do the capital placeholders come from?
问题描述
我正在尝试编写一个命令行界面(第一次),在阅读了关于 argparse
、optparse
和 getopt
之后,我之所以选择 argparse
,是因为这里有一些关于 SO 和网络中的 elswhere 的建议.改编了一点范罗苏姆先生的建议我连接了我的像这样的第一个命令行界面:
I am trying to write a command line interface (for the first time) and after reading up about argparse
, optparse
and getopt
I chose argparse
because of several recommendations here on SO and elswhere in the net. Adapting a little of the advice of Mr. van Rossum I hooked up my first command line interface like this:
def main(argv=None):
if argv is None:
argv = sys.argv
desc = u'some description'
parser = argparse.ArgumentParser(description=desc)
parser.add_argument('-s', '--search', help='Search for someone.')
parser.add_argument('-c', '--do_something_else', help='Do something else.')
args = parser.parse_args()
print args
if __name__ == '__main__':
sys.exit(main())
执行 python myscript.py -h
结果:
usage: dblp.py [-h] [-s SEARCH] [-c DO_SOMETHING_ELSE]
some description
optional arguments:
-h, --help show this help message and exit
-s SEARCH, --search SEARCH
Search for someone.
-c DO_SOMETHING_ELSE, --do_something_else DO_SOMETHING_ELSE
Do something else.
所以我的第一个问题是:为什么 SEARCH
和 DO_SOMETHING_ELSE
是用大写字母写的? 第二个问题是:我是否打破了任何标准?是否有更好的方法(或者我可以学习的一个很好的现实世界示例)如何使用 python 构建干净且有用的命令行界面? 是否存在应该避免的陷阱,写cmd接口的时候?
So my first question is: Why are SEARCH
and DO_SOMETHING_ELSE
written in CAPITAL LETTERS? The second question would be: Do I break any standards? Is there a better way (ore a nice real world example I can learn from) how to build clean and useful command line interfaces with python? And are there pitfalls one should avoid, when writing cmd interfaces?
推荐答案
以下是我挖掘的一些基本 argparse 资源:
Here are a couple basic argparse resources I dug up:
关于 argparse 的一些幻灯片:http://www.slideshare.net/tisto/argparse-python-command-line-parser
Some slides on argparse: http://www.slideshare.net/tisto/argparse-python-command-line-parser
一个小的 argparse 例子:http://www.rutherfurd.net/tag/argparse/
A little argparse example: http://www.rutherfurd.net/tag/argparse/
这是一个真实的 argparse 示例:https://github.com/harijay/xtaltools/blob/e685385a58d4b385387d485dceb38dce32a8585b/maskconvert.py
Here is a real-world argparse example: https://github.com/harijay/xtaltools/blob/e683fcef6a5ad7394b87382e58d4dce32a85585b/maskconvert.py
就避免陷阱而言,这里有一个漂亮的 argparse 包装器,用于减少您必须为一些常见用例编写的样板代码:http://travelingfrontiers.wordpress.com/2010/11/03/simple-python-argparse-wrapper/
As far as avoiding pitfalls, here is a nice looking wrapper for argparse to reduce the boilerplate code you have to write for some common usecases: http://travelingfrontiers.wordpress.com/2010/11/03/simple-python-argparse-wrapper/
这篇关于argparse python 模块行为的解释:大写占位符从哪里来?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!