Python argparse结合了一个标志和一个变量 [英] Python argparse combining a flag and a variable

查看:26
本文介绍了Python argparse结合了一个标志和一个变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望能够为我的程序指定一个选项,该选项既可用作标志又可用作变量.例如:我有一个名为--logging"的论点.如果未指定此参数,我希望将其设置为 false(即 action='store_true'),但如果指定了该参数,我想做两件事.1) 我想设置默认路径./log_file.log" 2) 我想允许用户指定不同的日志文件位置.

I would like to be able to specify an option to my program which acts as both a flag and as variable. For example: I have an argument called "--logging". If this argument is not specified, I'd like it to be set to false (i.e. action='store_true'), but if the argument is specified, I'd like to do two things. 1) I'd like to set a default path of "./log_file.log" and 2) I'd like to allow the user to specify a different log file location.

推荐答案

对,所以我想出了我自己的解决方案.它依赖于 nargs.首先是代码:

Right, so I've come up with my own solution for this one. It relies on nargs. Here is the code first:

#!/usr/bin/python
# example.py
import argparse

parser = argparse.ArgumentParser(description="Example of a single flag acting as a boolean and an option.")
parser.add_argument('--foo', nargs='?', const="bar", default=False)
args = parser.parse_args()

if args.foo:
  print args.foo
else:
  print "Using the default, boolean False."

鉴于这个例子,当我们在三种可能的情况下使用它时会发生以下情况:

Given that example, here is what happens when we use it in the three possible situations:

> ./example.py
  Using the default, boolean False.
> ./example.py --foo
  bar
> ./example.py --foo baz
  baz

希望以上内容是不言自明的.如果不是,那 nargs=' 是怎么回事?如果未指定标志,则将使用默认"值(在我们的示例中为布尔值 False),如果标志不带参数指定,则使用 const 值,如果标志带参数指定,则使用参数.注意不要在 False 周围加上任何引号;False 是内置类型(布尔值),'False' 或 "False" 将评估为真.

Hopefully the above is pretty self-explanatory. In case it isn't, what is going on is that nargs='?' will use the 'default' value if the flag is not specified (boolean False in our case), the const value if the flag is specified without arguments, and the argument if the flag is specified with an argument. Be careful to not put any quotes around False; False is a built in type (boolean) and 'False' or "False" will evaluate as true.

这篇关于Python argparse结合了一个标志和一个变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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