4

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!

2 Answers 2

6

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')
Sign up to request clarification or add additional context in comments.

1 Comment

So now I'm doing something like: parser.add_argument("--dryrun"). Unfortunately, now I get: usage: my_script.py [-h] [--dryrun DRYRUN] csv my_script.py: error: argument --dryrun: expected one argument
2

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.