Python argparse: Too few arguments
Solution 1
To add an optional --dry-run
argument, you may use the following snippet:
parser.add_argument('--dry-run', action='store_true')
Calling your script using python my_script.py csv_name.csv --dry-run
will result to args.dry_run
being True
. Not putting the option will result to it being False
Solution 2
When you use the following syntax:
parser.add_argument("csv")
parser.add_argument("dryrun")
You're adding these as positional -- required -- arguments. Only arguments with a leading dash or two are optional.
See the docs here:
The add_argument() method must know whether an optional argument, like -f or --foo, or a positional argument, like a list of filenames, is expected. The first arguments passed to add_argument() must therefore be either a series of flags, or a simple argument name. For example, an optional argument could be created like:
>>> parser.add_argument('-f', '--foo')
anon_swe
Updated on June 08, 2022Comments
-
anon_swe almost 2 years
I'm trying to use the argparse library in Python. I want to have the user do something like:
python my_script.py csv_name.csv [--dryrun]
where
--dryrun
is an optional parameter.I then have the user enter an API key and secret key. When I run my code, I get past entering the API and secret keys and then I get:
usage: my_script.py [-h] csv dryrun salesforceImporter.py: error: too few arguments
Here's my code:
def main(): api_key = getpass.getpass(prompt='Enter API Key: ') secret_key = getpass.getpass(prompt='Enter Secret Key: ') parser = argparse.ArgumentParser() parser.add_argument("csv") parser.add_argument("dryrun") args = parser.parse_args() validate_csv_name(args.csv) is_dry_run = args.dryrun == '--dryrun'
Any idea where I'm going wrong?
Thanks!