想要一个简单的argparse示例:1个参数,3个结果 [英] Simple argparse example wanted: 1 argument, 3 results
问题描述
The documentation for the argparse python module, while excellent I'm sure, is too much for my tiny beginner brain to grasp right now. I don't need to do math on the command line or meddle with formatting lines on the screen or change option characters. All I want to do is "If arg is A, do this, if B do that, if none of the above show help and quit".
推荐答案
我对原始问题的理解有两个方面.首先,就最简单的argparse示例而言,令我感到惊讶的是,我在这里没有看到它.当然,简而言之,这也是所有开销很小的开销,但这可能会让您入门.
My understanding of the original question is two-fold. First, in terms of the simplest possible argparse example, I'm surprised that I haven't seen it here. Of course, to be dead-simple, it's also all overhead with little power, but it might get you started.
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("a")
args = parser.parse_args()
if args.a == 'magic.name':
print 'You nailed it!'
但是现在需要此位置参数.如果在调用该程序时将其遗漏,则会出现有关缺少参数的错误.这将我引到原始问题的第二部分.马特·威尔基(Matt Wilkie)似乎想要一个单独的 optional 参数,而没有命名标签(--option标签).我的建议是修改上面的代码,如下所示:
But this positional argument is now required. If you leave it out when invoking this program, you'll get an error about missing arguments. This leads me to the second part of the original question. Matt Wilkie seems to want a single optional argument without a named label (the --option labels). My suggestion would be to modify the code above as follows:
...
parser.add_argument("a", nargs='?', default="check_string_for_empty")
...
if args.a == 'check_string_for_empty':
print 'I can tell that no argument was given and I can deal with that here.'
elif args.a == 'magic.name':
print 'You nailed it!'
else:
print args.a
也许会有一个更优雅的解决方案,但这是可行的,并且极简.
There may well be a more elegant solution, but this works and is minimalist.
这篇关于想要一个简单的argparse示例:1个参数,3个结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!