bclayman bclayman - 1 year ago 155
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]

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()
args = parser.parse_args()


is_dry_run = args.dryrun == '--dryrun'

Any idea where I'm going wrong?


Answer Source

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download