Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Argument for argparse always needed, I want to make it optional(without –)

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

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

parser.add_argument('string', type=str, help='String for additional info', nargs='*')
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading