Home > Blockchain >  Argument for argparse always needed, I want to make it optional(without --)
Argument for argparse always needed, I want to make it optional(without --)

Time:10-11

I've done my research but still couldn't find a way to be able to run a python with a random string as an argument and without any arguments at the same time.(without --)

import argparse

parser = argparse.ArgumentParser(description="Argument list")
parser.add_argument('string', type=str, help='String for additional info')
args = parser.parse_args()
if args.string :
    print("You passed an argument")
enter code here

Runs perfectly with argument - python main.py blablabla

Crashes - python main.py

main.py: error: the following arguments are required: string

I could use a key word like --string=blablabla, but I want to avoid key word part(--string=)

Is it possible to handle optional argument without using keywords?

CodePudding user response:

Pass nargs='*' to accept zero or more of a positional argument

parser.add_argument('string', type=str, help='String for additional info', nargs='*')
  • Related