7

I need to take an optional argument when running my Python script:

python3 myprogram.py afile.json

or

python3 myprogram.py

This is what I've been trying:

filename = 0
parser = argparse.ArgumentParser(description='Create Configuration')
parser.add_argument('filename', type=str,
                   help='optional filename')

if filename is not 0:
    json_data = open(filename).read()
else:
    json_data = open('defaultFile.json').read()

I was hoping to have the filename stored in my variable called "filename" if it was provided. Obviously this isn't working. Any advice?

4 Answers 4

9

Please read the tutorial carefully. http://docs.python.org/howto/argparse.html

i believe you need to actually parse the arguments:

parser = argparse.ArgumentParser()
args = parser.parse_args()

then filename will be come available args.filename

Sign up to request clarification or add additional context in comments.

Comments

8

Check sys.argv. It gives a list with the name of the script and any command line arguments.

Example script:

import sys
print sys.argv

Calling it:

> python script.py foobar baz
['script.py', 'foobar', 'baz']

Comments

4

If you are looking for the first parameter sys.argv[1] does the trick. More info here.

Comments

2

Try argparse's default parameter, its well documented.

import argparse

parser = argparse.ArgumentParser(description='Create Configuration')
parser.add_argument('--file-name', type=str, help='optional filename', 
       default="defaultFile.json")

args = parser.parse_args()

print(args.file_name)

Output:

$ python open.py --file-name option1
option1

$ python open.py 
defaultFile.json

Alternative library:

click library for arg parsing.

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.