def get_config(key=None, default=None, path="config.json"): """ 读取配置 """ if not hasattr(get_config, "config"): try: with open(path) as configfile: get_config.config = loadjson(configfile) get_config.time = stat(path).st_mtime except IOError: error(' Config file `%s` does not exist!' % path) with open(path, 'w') as configfile: configure = { "$schema": "https://ddns.newfuture.cc/schema/v2.8.json", "id": "YOUR ID or EMAIL for DNS Provider", "token": "YOUR TOKEN or KEY for DNS Provider", "dns": "dnspod", "ipv4": ["newfuture.cc", "ddns.newfuture.cc"], "ipv6": ["newfuture.cc", "ipv6.ddns.newfuture.cc"], "index4": "default", "index6": "default", "ttl": None, "proxy": None, "debug": False, } dumpjson(configure, configfile, indent=2, sort_keys=True) sys.stdout.write( "New template configure file `%s` is generated.\n" % path) sys.exit(1) except: sys.exit('fail to load config from file: %s' % path) if key: return get_config.config.get(key, default) else: return get_config.config
def write_json(filename, data, sort_keys=True, indent=4, separators=(',', ': ')): """ Write the dictionary to a JSON file. :param filename: file name (string). :param data: object to be written to file (dictionary or list). :param sort_keys: should entries be sorted? (boolean). :param indent: indentation level, default 4 (int). :param separators: field separators (default (',', ': ') for dictionaries, use e.g. (',\n') for lists) (tuple) :raises PilotException: FileHandlingFailure. :return: status (boolean). """ status = False try: with open(filename, 'w') as fh: dumpjson(data, fh, sort_keys=sort_keys, indent=indent, separators=separators) except IOError as exc: raise FileHandlingFailure(exc) else: status = True return status
def __load_config(path="config.json", skip_auto_generation=False): """ 加载配置 """ global __config, config_modified_time try: with open(path) as configfile: __config = loadjson(configfile) __config["config_modified_time"] = stat(path).st_mtime except IOError: if skip_auto_generation: __config["config_modified_time"] = time() return error(' Config file `%s` does not exist!' % path) with open(path, 'w') as configfile: configure = { "$schema": "https://ddns.newfuture.cc/schema/v2.8.json", "id": "YOUR ID or EMAIL for DNS Provider", "token": "YOUR TOKEN or KEY for DNS Provider", "dns": "dnspod", "ipv4": ["newfuture.cc", "ddns.newfuture.cc"], "ipv6": ["newfuture.cc", "ipv6.ddns.newfuture.cc"], "index4": "default", "index6": "default", "ttl": None, "proxy": None, "debug": False, } dumpjson(configure, configfile, indent=2, sort_keys=True) sys.stdout.write( "New template configure file `%s` is generated.\n" % path) sys.exit(1) except: sys.exit('fail to load config from file: %s' % path)
def main(): for pack in listdir('in'): if pack[0] != '.': for outdir in [ joinpath('out', pack, 'data'), joinpath('out', pack, 'textures', 'objects') ]: makedirs(outdir, exist_ok=True) default = {'tags': {}, 'sets': {}} for tag in listdir( joinpath('in', pack, 'textures', 'objects', 'tags')): default['tags'].update({ tag: [ f"textures/objects/{x}" for x in listdir( joinpath('in', pack, 'textures', 'objects', 'tags', tag)) ] }) for x in listdir( joinpath('in', pack, 'textures', 'objects', 'tags', tag)): copyfiles( joinpath('in', pack, 'textures', 'objects', 'tags', tag, x), joinpath('out', pack, 'textures', 'objects')) with open( joinpath('out', pack, 'data', 'default.dungeondraft_tags'), 'w+') as tagfile: dumpjson(default, tagfile, sort_keys=False, indent=4) return 0
def out_json(out_file: Path, syllabuses: SyllabusList, indent=2) -> Path: jobj = [ { 'label': syllabus.label, 'skills': [ { 'label': skill.label, 'items': skill.items } for skill in syllabus.skills ] } for syllabus in syllabuses ] with out_file.open('w') as f: dumpjson(jobj, f, ensure_ascii=False, indent=indent)
def new_setting(key, value): settings_path, settings_filename = find_settings_file() settings = load_settings(process_markers=False) # check whether the key is already in there if key in settings.keys(): logging.info("the key is already stored.") # pre-process the value if isinstance(value, str): value.replace('\n', '\\n') settings[key] = value # store the settings with open(settings_path, 'w') as file: dumpjson(settings, file) logging.info("new settings written.")
def main(): from docopt import docopt from json import dumps as dumpjson args = docopt(__doc__) patterns = args['PATTERNS'] limit = args['--limit'] sort_limit = args['--sort-limit'] options = {} if limit is not False and limit is not None: options['limit'] = int(limit) if sort_limit is not False and sort_limit is not None: options['sort_limit'] = int(sort_limit) if args['--ignore-bad-patterns']: options['ignore_bad_patterns'] = True if args['--reverse']: options['reverse'] = True strip = str.strip entries = (strip(line) for line in iter(sys.stdin.readline, '')) terms = (Term(i, c) for i, c in enumerate(entries, start=1) if c) results = filter_entries(terms, *patterns, **options) for result in results: if args['--output-json']: line = dumpjson(result.asdict()) else: line = build_line(result, highlight=not args['--no-color']) print(line) return 0
location = place.location point_geometry = {'type': 'Point', 'coordinates': (location.lon, location.lat)} point_features.append({'type': 'Feature', 'geometry': point_geometry, 'properties': properties }) label_geometry = bbox_polygon(place.label_bbox(), osm, zoom).__geo_interface__ label_features.append({'type': 'Feature', 'geometry': label_geometry, 'properties': properties }) dumpjson({'type': 'FeatureCollection', 'features': point_features}, open(pointsfile, 'w')) dumpjson({'type': 'FeatureCollection', 'features': label_features}, open(labelsfile, 'w')) print 'Wrote %d points to %s and %s.' % (len(point_features), pointsfile, labelsfile) print '-' * 80 map = mapByCenterZoom(osm, Location(0, 0), zoom, Point(2 ** (zoom + 8), 2 ** (zoom + 8))) if zoom > 5: map = mapByCenterZoom(osm, Location(40.078, -96.987), zoom, Point(1400, 800)) map = mapByCenterZoom(osm, Location(38.889, -77.050), zoom, Point(1200, 900)) img = map.draw(False) # newimg('RGB', (map.dimensions.x, map.dimensions.y), (0xFF, 0xFF, 0xFF)) draw = drawimg(img)