2

I need to access json file using command line argument

my code is python.py:

#########################################
import json
import sys
from sys import argv
from pprint import pprint

with open('cdh/cdh5.json') as data_file:
    data = json.load(data_file)

pprint(data['projects']['abcd']['track-branch'])

#################################################

so , instead of project abcd , i need to pass abcd from command line while executing this python script.

eg1: python.py abcd

will do : pprint(data['projects']['abcd']['track-branch'])

eg2: python.py efgh

will do : pprint(data['projects']['efgh']['track-branch'])

i tried doing this:-

pprint(data['projects']['sys.args']['track-branch']) but it gives me below error :

pprint(data['projects']['sys.argv']['track-branch'])
KeyError: 'sys.argv'

2 Answers 2

2

To access the arguments that you pass in from command line, you need to use sys.argv , you have got that correct.

But you should use it as it is, not pass that as a string , like what you are doing.

Also, sys.argv is a list of all the arguments from command line, the first element of sys.argv is the file that was executed (like python.py ). So you need to use second element. Example -

pprint(data['projects'][sys.argv[1]]['track-branch'])
Sign up to request clarification or add additional context in comments.

Comments

1

You're on the right track but sys.argv is an array with the main module at the 0th index and each successive command line argument at index 1, 2, etc. You should change your code to:

pprint(data['projects'][sys.argv[1]]['track-branch'])

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.