-1
我是一个新的python.I读取源代码并得到一些疑问。在Python中键入“字符串”到“字典”
if config_path:
logging.info('loading config from %s' % config_path)
with open(config_path, 'rb') as f:
try:
**config = parse_json_in_str(f.read().decode('utf8'))**
except ValueError as e:
logging.error('found an error in config.json: %s',
e.message)
sys.exit(1)
else:
config = {}
变量 “配置” 是这里的字符串(parse_json_in_str)。这里是parse_json_in_str:
def parse_json_in_str(data):
# parse json and convert everything from unicode to str
return json.loads(data, object_hook=_decode_dict)
然后:
v_count = 0
for key, value in optlist:
if key == '-p':
config['server_port'] = int(value)
elif key == '-k':
config['password'] = to_bytes(value)
elif key == '-l':
config['local_port'] = int(value)
elif key == '-s':
config['server'] = to_str(value)
elif key == '-m':
config['method'] = to_str(value)
elif key == '-b':
config['local_address'] = to_str(value)
elif key == '-v':
v_count += 1
# '-vv' turns on more verbose mode
config['verbose'] = v_count
elif key == '-t':
config['timeout'] = int(value)
.....
elif key == '-q':
v_count -= 1
config['verbose'] = v_count
except getopt.GetoptError as e:
print(e, file=sys.stderr)
print_help(is_local)
sys.exit(2)
为什么 “配置” 变成字典?
没有'parse_json_in_str'我们无法理解代码;但我想它是这么做的:在一个字符串中解析一些JSON并返回解析的值;在这种情况下,这似乎是一个字典。 – bfontaine
parse_json_in_str prolly需要一个字符串并返回一个字典?不知道没有看到它。 – Jacobr365
谢谢,bfontaine。 – zhan