Framework argparse - check if flag is set

10,510

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
Share:
10,510
Bartłomiej Bartnicki
Author by

Bartłomiej Bartnicki

Student at Jagiellonian University (Poland) - Computer Science. intrest: - web technologies (js, Dart, HTML5, canvas, Angular, Jetty) QA - Engineering: Selenium, theory of testing

Updated on June 10, 2022

Comments

  • Bartłomiej Bartnicki
    Bartłomiej Bartnicki almost 2 years

    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()