2016-06-13 2 views
1

json 파일 매개 변수를 명령 줄 인수 파서를 통해 파이썬 사전에 덮어 써야합니다. 이후, JSON 파일은 현재 작업 디렉토리에 위치하지만, 그 이름은 동적 일 수있다, 그래서 나는 다음과 같은 무언가를 원하는 : -json 파일을 파서를 통해 명령 줄 인수로 전달할 수 있습니까?

파이썬 python_script --infile json_file

python_script :

if __name__ == "__main__": 
    profileInfo = dict() 
    profileInfo['profile'] = "enterprisemixed" 
    profileInfo['nodesPerLan'] = 50 

json_file는 :

{ 
    "profile":"adhoc",    
    "nodesPerLan" : 4 
} 

나는 다음의 리터를 추가하려고 아이 네스는하지만, 파이썬 사전에이 JSON 데이터를로드하는 방법을 모른다 : -

import argparse 
parser = argparse.ArgumentParser() 
parser.add_argument('--infile', nargs = 1, help="JSON file to be processed",type=argparse.FileType('r')) 
arguments = parser.parse_args() 
+1

음, 읽기 python doc로 충분해야합니다. 파일 : https://docs.python.org/3/tutorial/inputoutput.html JSON 부분 : https://docs.python.org/3.5/library/json.html args : lib를 사용하십시오. –

+0

@fmarc 위의 코드를 시도했습니다. 파이썬에 익숙하지 않습니다. json load 메서드에 대해 알고 있지만 특정 파일 만로드합니다.이 경우에는 내 경우에 감사하지 않습니다. –

답변

0

--infile에 주어진 이름으로 JSON 파일을 읽고 당신의 profileInfo 업데이트 :

import json 
import argparse 

parser = argparse.ArgumentParser() 
parser.add_argument('--infile', nargs=1, 
        help="JSON file to be processed", 
        type=argparse.FileType('r')) 
arguments = parser.parse_args() 

# Loading a JSON object returns a dict. 
d = json.load(arguments.infile[0]) 

profileInfo = {} 
profileInfo['profile'] = "enterprisemixed" 
profileInfo['nodesPerLan'] = 50 

print(profileInfo) 
# Overwrite the profileInfo dict 
profileInfo.update(d) 
print(profileInfo) 
+0

위대한! 이건 내가 정확히 gomawoyo를 찾고 있었던 것이다! @Nightcrawler –

+1

더 동적 인 해결책이 있습니까? 사전에 파일 이름을 모른다고 해봅시다. Json 파일에서 매개 변수를 지원할 수있는 도구가 있으면 좋을 것입니다. – Alex

관련 문제