繁体   English   中英

argparse:store_true和int同时出现

[英]argparse: store_true and int at same time

我正在使用argparse作为cli参数。 我想要一个参数-t来进行温度测试。 我还想指定温度测量的周期。

我想要:

python myscript.py -t每60秒执行一次测量,

python myscript.py -t 30每30秒进行一次测量,

python myscript.py不做温度测量。

现在我这样做:

parser.add_argument('-t', '--temperature',
                    help='performs temperature test (period in sec)',
                    type=int, default=60, metavar='PERIOD')

问题是我无法区分python myscript.pypython myscript.py -t

它希望能够同时执行类似action='store_true'type=int的操作。 可能吗? 还有其他办法吗?

谢谢!

使用const参数:

import argparse
parser = argparse.ArgumentParser()
parser.add_argument(
    '-t', '--temperature',
    help='performs temperature test (period in sec)',
    type=int,
    nargs='?',
    const=60,         # Default value if -t is supplied
    default=None,     # Default value if -t is not supplied
    metavar='PERIOD')

args = parser.parse_args()
print(args)

% test.py
Namespace(temperature=None)
% test.py -t
Namespace(temperature=60)
% test.py -t 30
Namespace(temperature=30)

我以前没用过argparse。 但是最近我在docopt https://github.com/docopt/docopt上看到了一个让我感到震惊的演示文稿。

也许试一试?

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM