Python argparse command line flags without arguments

后端 未结 4 685
南旧
南旧 2020-12-12 10:19

How do I add an optional flag to my command line args?

eg. so I can write

python myprog.py 

or

python myprog.py -w         


        
相关标签:
4条回答
  • 2020-12-12 10:37

    As you have it, the argument w is expecting a value after -w on the command line. If you are just looking to flip a switch by setting a variable True or False, have a look here (specifically store_true and store_false)

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

    where action='store_true' implies default=False.

    Conversely, you could haveaction='store_false', which implies default=True.

    0 讨论(0)
  • 2020-12-12 10:41

    Here's a quick way to do it, won't require anything besides sys.. though functionality is limited:

    flag = "--flag" in sys.argv[1:]

    [1:] is in case if the full file name is --flag

    0 讨论(0)
  • 2020-12-12 10:50

    Your script is right. But by default is of None type. So it considers true of any other value other than None is assigned to args.argument_name variable.

    I would suggest you to add a action="store_true". This would make the True/False type of flag. If used its True else False.

    import argparse
    parser = argparse.ArgumentParser('parser-name')
    parser.add_argument("-f","--flag",action="store_true",help="just a flag argument")
    

    usage

    $ python3 script.py -f
    

    After parsing when checked with args.f it returns true,

    args = parser.parse_args()
    print(args.f)
    
    >>>true
    
    0 讨论(0)
  • 2020-12-12 10:51

    Adding a quick snippet to have it ready to execute:

    Source: myparser.py

    import argparse
    parser = argparse.ArgumentParser(description="Flip a switch by setting a flag")
    parser.add_argument('-w', action='store_true')
    
    args = parser.parse_args()
    print args.w
    

    Usage:

    python myparser.py -w
    >> True
    
    0 讨论(0)
提交回复
热议问题