저는 파이썬 초보자입니다. json 형식의 파일에있는 프로그램 매개 변수를 처리하는 것에 대한 조언을 원합니다. 현재, 나는 아래에 보여지는 것과 같은 것을하고있다. 그러나 그것은 너무 어리석은 것처럼 보이고, 동일한 리터럴 문자열을 여러 번 (때로는 대시와 밑줄을 사용하여) 타이핑하는 생각은 청소년 오류가있는 것처럼 보인다. -) (더 많은 매개 변수가 있습니다!)json 파일의 파이썬 프로그램 인수 처리
#!/usr/bin/env python
import sys
import os
import json ## for control file parsing
# control parameters
mpi_nodes = 1
cluster_size = None
initial_cutoff = None
# ...
#process the arguments
if len(sys.argv) != 2:
raise Exception(
"""Usage:
run_foo <controls.json>
Where:
<control.json> is a dictionary of run parameters
"""
)
# We expect a .json file with our parameters
controlsFileName = sys.argv[1]
err = ""
err += "" #validateFileArgument(controlsFileName, exists=True)
# read in the control parameters from the .json file
try:
controls = json.load(open(controlsFileName, "r"))
except:
err += "Could not process the file '" + controlsFileName + "'!\n"
# check each control parameter. The first one is optional
if "mpi-nodes" in controls:
mpi_nodes = controls["mpi-nodes"]
else:
mpi_nodes = controls["mpi-nodes"] = 1
if "cluster-size" in controls:
cluster_size = controls["cluster-size"]
else:
err += "Missing control definition for \"cluster-size\".\n"
if "initial-cutoff" in controls:
initial_cutoff = controls["initial-cutoff"]
else:
err += "Missing control definition for \"initial-cutoff\".\n"
# ...
# Quit if any of these things were not true
if len(err) > 0:
print err
exit()
#...
이 방법이 효과적이지만 더 나은 방법이 있어야합니다. json 파일을 사용하고 하이픈이 연결된 매개 변수 이름을 사용하는 데 필요한 요구 사항이 있습니다. 어떤 아이디어?
정적 바인딩이 더 필요합니다. 아마 이것은 그것이 얻는만큼 좋다.
무엇이 문제입니까? "뚱뚱한"이 무슨 뜻이야? 어떻게하면 좋을지에 대한 예를 들어 줄 수 있습니까? –
Slott, 그냥 말투로 보인다. 그리고 (실제적으로) 똑같은 문자열을 여러 번 입력하는 전체 아이디어는 청소년처럼 보입니다 - 오류가 발생하기 쉽습니다 ... ----- 나는 더 많은 매개 변수를 가지고 있습니다! –
의견이 아닌 질문의 입장을 설명해주십시오. ** 당신이 싫어하는 것을 밝히기 위해 질문을 ** 업데이트하십시오. –