bclayman bclayman - 5 months ago 33
Python Question

Python argparse: Too few arguments

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!

Answer

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

Comments