Kuratorn
Kuratorn

Reputation: 305

Python argparse with possibly empty string value

I would like to use argparse to pass some values throughout my main function. When calling the python file, I would always like to include the flag for the argument, while either including or excluding its string argument. This is because some external code, where the python file is being called, becomes a lot simpler if this would be possible.

When adding the arguments by calling parser.add_argument, I've tried setting the default value to default=None and also setting it to default=''. I can't make this work on my own it seems..

def main():
    parser = argparse.ArgumentParser()
    parser.add_argument('-p', '--projects_to_build', default='')
    args = parser.parse_args()

This call works fine:

py .\python_file.py -p proj_1,proj_2,proj_3

This call does not:

py .\python_file.py -p

python_file.py: error: argument -p/--projects_to_build: expected one argument

Upvotes: 17

Views: 20603

Answers (1)

Patrick Haugh
Patrick Haugh

Reputation: 60994

You need to pass a nargs value of '?' with const=''

parser.add_argument('-p', '--projects_to_build', nargs='?', const='')

You should also consider adding required=True so you don't have to pass default='' as well.

Upvotes: 19

Related Questions