Framework argparse - check if flag is set

不羁的心 提交于 2019-12-23 16:58:32

问题


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

My code:

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

It is possible to write it in this way

python script.py -x

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

回答1:


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


来源:https://stackoverflow.com/questions/32884131/framework-argparse-check-if-flag-is-set

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!