Take the string argument from the Python command line

advertisements

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?


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