1

I'm a little confused about the use of the default keyword argument for the add_argument() method in argparse. Here's a really simple script I ran to see how arguments are parsed:

import argparse
parser = argparse.ArgumentParser()
parser.add_argument('some_string', default = 'hello world')
args = parser.parse_args()
print(args.some_string)

When I run this in my terminal and provide an argument, it parses correctly:

$ python argparse_test.py "hello world"
> hello world

When I run this in my terminal and omit an argument, I get an error:

$ python argparse_test.py
> argparse_test.py: error: the following arguments are required: some_string

Am I overlooking something simple?

strato
  • 47
  • 3

1 Answers1

1

You are specifying a positional argument, which are required. You probably wanted a keyword argument instead, something like --some_string. If you have enough unique letters, you may also wanna specify an alias for it, like -s. Now you can run it like

  • python argparse_test.py
  • python argparse_test.py --some_string="hello world"
Harsh
  • 395
  • 2
  • 7