框架 argparse - 检查是否设置了标志 [英] Framework argparse - check if flag is set

查看:30
本文介绍了框架 argparse - 检查是否设置了标志的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想这样使用我的脚本:python script.py -x现在我使用这个命令运行它 python script.py -x y

I want to use my script in this way: python script.py -x now I run it using this command python script.py -x y

我的代码:

parser = ArgumentParser()
parser.add_argument('-x', '--x', dest="x", default="n")
options = parser.parse_args()
if option.x == 'y':
    f()

可以这样写

python script.py -x

parser = ArgumentParser()
parser.add_argument('-x', '--x', dest="x")
options = parser.parse_args()
if isset(option.x):
    f()

推荐答案

只需使用 'store_true' 动作:

Just use the 'store_true' action:

import argparse

parser = argparse.ArgumentParser()
parser.add_argument('-x', action='store_true')

然后你可以简单地测试这个论点的真实性:

then you can simply test for the truthiness of that argument:

options = parser.parse_args()
if options.x:
    f()

在使用中,只打印该参数是否为真:

In use, just printing whether or not that argument is truth-y:

C:\Python27>python so.py
x is not set

C:\Python27>python so.py -x
x is set

这篇关于框架 argparse - 检查是否设置了标志的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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