Search code examples
pythonpython-2.7parsingif-statementargs

How to use conditional statements with argparse?


So I have created my argparse which has two different flags. One is -a and the other one is -b. When I run my script damage.py with a specific flag, I want it to be able to execute a function depending on what flag is passed. For example if I pass damage.py -t, it will run the function tester() as shown in my import and print hello, where as if I pass -d it will run another function. So far my code is as follows:

import argparse


def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("-a", "--export-date", action="store_true", required=True)
    parser.add_argument("-b", "--execute-test", action="store_true", required=False)


if __name__ == '__main__':
    main()

Solution

  • Rather than saving these values to a variable first you can access them directly like this:

    if args.export_date:
        # Do something with date
    
    if args.execute_test:
        tester()
    

    This means that when you run your program like python damage.py -dt it will run both the code in the date block as in the tester block.