3

I am new on python. I am using a python script where I load a json file to set certain values to the script, but my idea is to import that file more dynamically using arguments (I think is the correct use), so I don“t need to always include the name of the json file in the python script, here is may code example:

import json
from pprint import pprint

with open("VariableSettings.json") as json_data:
    data = json.load(json_data)

so my idea is to change the code: "with open("VariableSettings.json") as json_data" with args to open the json file dynamically.

I think that on command prompt I can use the command py test.py arg1 (this represent the file path).

So I know that probably my explanation is a bit confusing but if some can help I appreciate it.

James Z
  • 12,209
  • 10
  • 24
  • 44
Rui Ferreira
  • 39
  • 2
  • 6

3 Answers3

5

You can use sys to do that. In the example below I created a file test.json with the content

{"foo": "bar"}

And modified your code as

import json
import sys

with open(sys.argv[1]) as json_data:
    data = json.load(json_data)
    print(data)

You need to call execute as

python test.py test.json

and the output will be

{'foo': 'bar'}

More details can be found in this other post

caverac
  • 1,505
  • 2
  • 12
  • 17
4

You can also use argparse:

import json
import argparse

parser = argparse.ArgumentParser()
parser.add_argument("-f", "--filename", required=True, type=str)
args = parser.parse_args()

with open(args.filename) as json_data:
    data = json.load(json_data)
    print(data)

Which can be called with the alias:

python test.py -f test.json

Or full argument name:

python test.py --filename test.json

And if you don't supply a file, you get:

usage: test.py [-h] -f FILENAME
test.py: error: the following arguments are required: -f/--filename

since I passed required=True. You can remove this if you want the argument to be optional.

Addtionally, you could also extend your program to check that if the JSON file has correct format by catching json.JSONDecodeError with try/except:

with open(args.filename) as json_data:
    try:        
        data = json.load(json_data)
        print(data)
    except json.JSONDecodeError:
        print('Invalid JSON format')
RoadRunner
  • 25,803
  • 6
  • 42
  • 75
2

Use the sys module

Ex:

import sys
import json
from pprint import pprint

if len(sys.argv) < 2:
    print("Input File Missing")
    sys.exit()

with open(sys.argv[1]) as json_data:
    data = json.load(json_data)
print(data)

To Run Use

python yourScriptName.py full_path_to.json
Rakesh
  • 81,458
  • 17
  • 76
  • 113