Take string argument from command line?
Asked Answered
T

4

6

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?

Trentontrepan answered 3/10, 2012 at 18:18 Comment(0)
H
8

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

Heeheebiejeebies answered 3/10, 2012 at 18:22 Comment(0)
J
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']
Jhelum answered 3/10, 2012 at 18:22 Comment(0)
H
8

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

Heeheebiejeebies answered 3/10, 2012 at 18:22 Comment(0)
A
4

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

Abigailabigale answered 3/10, 2012 at 18:22 Comment(0)
V
1

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.

Varnish answered 23/2, 2022 at 20:31 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.