本文整理汇总了Python中json5.dumps方法的典型用法代码示例。如果您正苦于以下问题:Python json5.dumps方法的具体用法?Python json5.dumps怎么用?Python json5.dumps使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类json5
的用法示例。
在下文中一共展示了json5.dumps方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: main
# 需要导入模块: import json5 [as 别名]
# 或者: from json5 import dumps [as 别名]
def main():
argv = sys.argv
if len(argv) == 2:
arg_groups = params.parse(sys.argv[1])
for args, config in arg_groups:
trainer = Trainer(args)
states = trainer.train()
with open('models/log.jsonl', 'a') as f:
f.write(json5.dumps({
'data': os.path.basename(args.data_dir),
'params': config,
'state': states,
}))
f.write('\n')
elif len(argv) == 3 and '--dry' in argv:
argv.remove('--dry')
arg_groups = params.parse(sys.argv[1])
pprint([args.__dict__ for args, _ in arg_groups])
else:
print('Usage: "python train.py configs/xxx.json5"')
示例2: test_skip_keys
# 需要导入模块: import json5 [as 别名]
# 或者: from json5 import dumps [as 别名]
def test_skip_keys(self):
od = OrderedDict()
od[(1, 2)] = 2
self.assertRaises(TypeError, json5.dumps, od)
self.assertEqual(json5.dumps(od, skipkeys=True), '{}')
od['foo'] = 1
self.assertEqual(json5.dumps(od, skipkeys=True), '{foo: 1}')
# Also test that having an invalid key as the last element
# doesn't incorrectly add a trailing comma (see
# https://github.com/dpranke/pyjson5/issues/33).
od = OrderedDict()
od['foo'] = 1
od[(1, 2)] = 2
self.assertEqual(json5.dumps(od, skipkeys=True), '{foo: 1}')
示例3: _render
# 需要导入模块: import json5 [as 别名]
# 或者: from json5 import dumps [as 别名]
def _render(self):
""" Writes the current config to file. """
new_config = json5.dumps(self.config)
with open(self.path, 'w') as f:
log.info('rewriting ContainerPilot config: %s', new_config)
f.write(new_config)
示例4: check
# 需要导入模块: import json5 [as 别名]
# 或者: from json5 import dumps [as 别名]
def check(self, obj, s):
self.assertEqual(json5.dumps(obj), s)
示例5: test_allow_duplicate_keys
# 需要导入模块: import json5 [as 别名]
# 或者: from json5 import dumps [as 别名]
def test_allow_duplicate_keys(self):
self.assertIn(json5.dumps({1: "foo", "1": "bar"}),
{'{"1": "foo", "1": "bar"}',
'{"1": "bar", "1": "foo"}'})
self.assertRaises(ValueError, json5.dumps,
{1: "foo", "1": "bar"},
allow_duplicate_keys=False)
示例6: test_check_circular
# 需要导入模块: import json5 [as 别名]
# 或者: from json5 import dumps [as 别名]
def test_check_circular(self):
# This tests a trivial cycle.
l = [1, 2, 3]
l[2] = l
self.assertRaises(ValueError, json5.dumps, l)
# This checks that json5 doesn't raise an error. However,
# the underlying Python implementation likely will.
try:
json5.dumps(l, check_circular=False)
self.fail() # pragma: no cover
except Exception as e:
self.assertNotIn(str(e), 'Circular reference detected')
# This checks that repeated but non-circular references
# are okay.
x = [1, 2]
y = {"foo": x, "bar": x}
self.check(y,
'{foo: [1, 2], bar: [1, 2]}')
# This tests a more complicated cycle.
x = {}
y = {}
z = {}
z['x'] = x
z['y'] = y
z['x']['y'] = y
z['y']['x'] = x
self.assertRaises(ValueError, json5.dumps, z)
示例7: test_default
# 需要导入模块: import json5 [as 别名]
# 或者: from json5 import dumps [as 别名]
def test_default(self):
def _custom_serializer(obj):
del obj
return 'something'
self.assertRaises(TypeError, json5.dumps, set())
self.assertEqual(json5.dumps(set(), default=_custom_serializer),
'something')
示例8: test_ensure_ascii
# 需要导入模块: import json5 [as 别名]
# 或者: from json5 import dumps [as 别名]
def test_ensure_ascii(self):
self.check(u'\u00fc', '"\\u00fc"')
self.assertEqual(json5.dumps(u'\u00fc', ensure_ascii=False),
u'"\u00fc"')
示例9: test_numbers
# 需要导入模块: import json5 [as 别名]
# 或者: from json5 import dumps [as 别名]
def test_numbers(self):
self.check(15, '15')
self.check(1.0, '1.0')
self.check(float('inf'), 'Infinity')
self.check(float('-inf'), '-Infinity')
self.check(float('nan'), 'NaN')
self.assertRaises(ValueError, json5.dumps,
float('inf'), allow_nan=False)
示例10: test_non_string_keys
# 需要导入模块: import json5 [as 别名]
# 或者: from json5 import dumps [as 别名]
def test_non_string_keys(self):
self.assertEqual(json5.dumps({False: 'a', 1: 'b', 2.0: 'c', None: 'd'}),
'{"false": "a", "1": "b", "2.0": "c", "null": "d"}')
示例11: test_quote_keys
# 需要导入模块: import json5 [as 别名]
# 或者: from json5 import dumps [as 别名]
def test_quote_keys(self):
self.assertEqual(json5.dumps({"foo": 1}, quote_keys=True),
'{"foo": 1}')
示例12: test_sort_keys
# 需要导入模块: import json5 [as 别名]
# 或者: from json5 import dumps [as 别名]
def test_sort_keys(self):
od = OrderedDict()
od['foo'] = 1
od['bar'] = 2
self.assertEqual(json5.dumps(od, sort_keys=True),
'{bar: 2, foo: 1}')
示例13: test_empty_key
# 需要导入模块: import json5 [as 别名]
# 或者: from json5 import dumps [as 别名]
def test_empty_key(self):
self.assertEqual(json5.dumps({'': 'value'}), '{"": "value"}')
示例14: test_object_roundtrip
# 需要导入模块: import json5 [as 别名]
# 或者: from json5 import dumps [as 别名]
def test_object_roundtrip(self, input_object):
dumped_string_json = json.dumps(input_object)
dumped_string_json5 = json5.dumps(input_object)
parsed_object_json = json5.loads(dumped_string_json)
parsed_object_json5 = json5.loads(dumped_string_json5)
assert parsed_object_json == input_object
assert parsed_object_json5 == input_object
示例15: __init__
# 需要导入模块: import json5 [as 别名]
# 或者: from json5 import dumps [as 别名]
def __init__(self, config, resume, model, optimizer, loss_function):
self.n_gpu = torch.cuda.device_count()
self.device = self._prepare_device(self.n_gpu, cudnn_deterministic=config["cudnn_deterministic"])
self.model = model.to(self.device)
if self.n_gpu > 1:
self.model = torch.nn.DataParallel(self.model, device_ids=list(range(self.n_gpu)))
self.optimizer = optimizer
self.loss_function = loss_function
# Trainer
self.epochs = config["trainer"]["epochs"]
self.save_checkpoint_interval = config["trainer"]["save_checkpoint_interval"]
self.validation_config = config["trainer"]["validation"]
self.validation_interval = self.validation_config["interval"]
self.find_max = self.validation_config["find_max"]
self.validation_custom_config = self.validation_config["custom"]
self.start_epoch = 1
self.best_score = -np.inf if self.find_max else np.inf
self.root_dir = Path(config["root_dir"]) / config["experiment_name"]
self.checkpoints_dir = self.root_dir / "checkpoints"
self.logs_dir = self.root_dir / "logs"
prepare_empty_dir([self.checkpoints_dir, self.logs_dir], resume=resume)
self.writer = visualization.writer(self.logs_dir.as_posix())
self.writer.add_text(
tag="Configuration",
text_string=f"<pre> \n{json5.dumps(config, indent=4, sort_keys=False)} \n</pre>",
global_step=1
)
if resume: self._resume_checkpoint()
print("Configurations are as follows: ")
print(json5.dumps(config, indent=2, sort_keys=False))
with open((self.root_dir / f"{time.strftime('%Y-%m-%d-%H-%M-%S')}.json").as_posix(), "w") as handle:
json5.dump(config, handle, indent=2, sort_keys=False)
self._print_networks([self.model])