框架argparse-检查是否设置了标志 [英] Framework argparse - check if flag is set
本文介绍了框架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()
在使用中,只需打印该参数是否为真-y:
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屋!
查看全文