想要的简单 argparse 示例:1 个参数,3 个结果 [英] Simple argparse example wanted: 1 argument, 3 results

查看:16
本文介绍了想要的简单 argparse 示例:1 个参数,3 个结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

文档.com/PyMOTW/argparse/" rel="noreferrer">argparse python 模块,虽然我敢肯定,它非常好,但我的小初学者大脑现在无法掌握.我不需要在命令行上进行数学运算或干预屏幕上的格式化行或更改选项字符.我想要做的就是如果 arg 是 A,则执行此操作,如果 B 执行此操作,如果以上均未显示帮助并退出".

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 似乎想要一个没有命名标签(--option 标签)的 optional 参数.我的建议是将上面的代码修改如下:

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆