Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Take string argument from Python command line

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?

like image 741
Kreuzade Avatar asked Oct 03 '12 18:10

Kreuzade


3 Answers

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

like image 128
dm03514 Avatar answered Oct 01 '22 15:10

dm03514


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']
like image 37
Junuxx Avatar answered Oct 01 '22 16:10

Junuxx


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

like image 36
Damian Schenkelman Avatar answered Oct 01 '22 16:10

Damian Schenkelman