Search code examples
pythonpython-3.xcommand-linecommand-line-argumentsargparse

how to pass multiple flags in argparse python


I am trying to pass multiple flags, basically two flags. This is what my code looks like

parser.add_argument('--naruto', action='store_true')
parser.add_argument('--transformers', action='store_true')
parser.add_argument('--goku', action='store_true')
parser.add_argument('--anime', action='store_true')

I know action='store_true' makes it a flag. basically in the command line I will pass the arguments like => nameOfTheScript.py --goku --anime and based on this later on I will be checking if "anime" was sent as an argument do x else do y. how can I achieve something like this?


Solution

  • If I understand it correctly you ask how you can parse those args. Here is an example of argument parsing:

    parser.add_argument('--naruto', action='store_true')
    parser.add_argument('--transformers', action='store_true')
    parser.add_argument('--goku', action='store_true')
    parser.add_argument('--anime', action='store_true')
    
    args = parser.parse_args()
    
    # You can access your args with dot notation
    if args.goku:
      print("goku arg was passed in")
    
    if args.anime:
      print("anime arg was passed in")