def save(toml_config, config_path=None):
"""
:param toml_config: TOML configuration object
:type toml_config: MutableToml or Toml
:param config_path: path to config to use
:type config_path: str
"""
serial = toml.dumps(toml_config._dictionary)
if config_path is None:
config_path = get_config_path()
util.ensure_file_exists(config_path)
util.enforce_file_permissions(config_path)
with util.open_file(config_path, 'w') as config_file:
config_file.write(serial)
python类dumps()的实例源码
def write_toml(self, data, path=None):
"""Writes the given data structure out as TOML."""
if path is None:
path = self.pipfile_location
try:
formatted_data = contoml.dumps(data).rstrip()
except Exception:
for section in ('packages', 'dev-packages'):
for package in data[section]:
# Convert things to inline tables — fancy :)
if hasattr(data[section][package], 'keys'):
_data = data[section][package]
data[section][package] = toml._get_empty_inline_table(dict)
data[section][package].update(_data)
formatted_data = toml.dumps(data).rstrip()
formatted_data = cleanup_toml(formatted_data)
with open(path, 'w') as f:
f.write(formatted_data)
def write_table(self):
"""
|write_table| with
`TOML <https://github.com/toml-lang/toml>`__ format.
:raises pytablewriter.EmptyTableNameError:
If the |header_list| is empty.
:raises pytablewriter.EmptyHeaderError:
If the |header_list| is empty.
:Example:
:ref:`example-toml-table-writer`
"""
self._logger.logging_start_write()
self._verify_property()
self.stream.write(toml.dumps(self.tabledata.as_dict()))
self._logger.logging_complete_write()
def policy_from_crawl(prof):
conf = {}
conf['scripts'] = {}
opts = []
hosts = []
if not prof['js_sources'] and not prof['inline']:
conf['scripts']['allow'] = 'none'
return conf
if prof['js_sources']:
conf['scripts']['allow'] = 'custom'
for source in prof['js_sources']:
if source == 'HOME':
opts.append('self')
else:
hosts.append(source)
if prof['inline']:
opts.append('inline')
conf['scripts']['options'] = opts
conf['scripts']['hosts'] = hosts
return toml.dumps(conf)
def write(self, content, config_file):
with open(config_file, "w+") as conffile:
conffile.write(toml.dumps(content))
def write(self, content, config_file):
with open(config_file, "w+") as conffile:
conffile.write(json.dumps(content))
def create_pipfile():
data = {
"source": [{
"url": "https://pypi.python.org/simple",
"verify_ssl": True,
}],
"packages": {},
"dev-packages": {},
}
with open("Pipfile", "w") as f:
f.write(format_toml(toml.dumps(data)))
def write_front_matter(meta, style="toml"):
if style == "json":
import json
return json.dumps(meta, indent=4, sort_keys=True)
elif style == "toml":
import toml
return "+++\n" + toml.dumps(meta) + "+++\n"
elif style == "yaml":
import yaml
return "---\n" + yaml.dump(meta) + "---\n"
return ""
def getFrontMatter(item, format="toml"):
frontmatter = dict()
frontmatter["title"] = item["title"]
frontmatter["id"] = item["id"]
if "labels" in item:
frontmatter["tags"] = item["labels"]
frontmatter["aliases"] = [item["url"]]
frontmatter["publishdate"] = item["published"]
frontmatter["draft"] = False
frontmatter["date"] = item["published"]
frontmatter["lastmod"] = item["updated"]
if format == "toml":
return toml.dumps(frontmatter)
def printPosts(item, fields, docFormat=None, writeToFiles=False):
template = """+++
{0}
+++
{1}
"""
logger.debug(json.dumps(item,
sort_keys=True,
indent=2,
separators=(',', ': ')))
if docFormat:
logger.debug("Starting to print %s", item['id'])
filename = None
content = item["content"].encode('utf-8', "ignore")
if writeToFiles:
filename = getFilenameFromPostUrl(item['url'], docFormat)
with open(filename, "wb") as outputFile:
outputFile.write(content)
converted = pypandoc.convert_file(
filename,
docFormat,
format="html")
content = template.format(getFrontMatter(item),
converted).encode('utf-8',
'ignore')
with open(filename, "wb") as outputfile:
outputfile.write(content)
else:
print(content)
logger.info("Finished print %s: %s", item['id'], filename)
elif isinstance(fields, basestring):
fields = fields.split(",")
line = [str(item[k]) for k in fields if k in item]
print(",".join(line))
def parsed_pipfile(self):
# Open the pipfile, read it into memory.
with open(self.pipfile_location) as f:
contents = f.read()
# If any outline tables are present...
if ('[packages.' in contents) or ('[dev-packages.' in contents):
data = toml.loads(contents)
# Convert all outline tables to inline tables.
for section in ('packages', 'dev-packages'):
for package in data.get(section, {}):
# Convert things to inline tables — fancy :)
if hasattr(data[section][package], 'keys'):
_data = data[section][package]
data[section][package] = toml._get_empty_inline_table(dict)
data[section][package].update(_data)
# We lose comments here, but it's for the best.)
try:
return contoml.loads(toml.dumps(data, preserve=True))
except RuntimeError:
return toml.loads(toml.dumps(data, preserve=True))
else:
# Fallback to toml parser, for large files.
try:
return contoml.loads(contents)
except Exception:
return toml.loads(contents)
def _dumps(obj, fmt=None):
if fmt == 'toml':
return toml.dumps(obj)
elif fmt == 'json':
return json.dumps(obj, sort_keys=True, indent=2, default=json_util.default)
elif fmt == 'python':
return pformat(obj, indent=2)
elif fmt == 'pickle':
return pickle.dumps(obj)
else:
return str(obj)
def to_toml_string(self):
return str(toml.dumps(self.to_dict())).strip().split('\n')
def to_toml_string(self):
return str(toml.dumps(self.to_dict())).strip().split('\n')
def to_toml_string(self):
return str(toml.dumps(self.to_dict())).strip().split('\n')
def to_toml_string(self):
return str(toml.dumps(self.to_dict())).strip().split('\n')
def to_toml_string(self):
return str(toml.dumps(self.to_dict())).strip().split('\n')
def to_toml_string(self):
return str(toml.dumps(self.to_dict())).strip().split('\n')
def save(toml_config):
"""
:param toml_config: TOML configuration object
:type toml_config: MutableToml or Toml
"""
serial = toml.dumps(toml_config._dictionary)
path = util.get_config_path()
with util.open_file(path, 'w') as config_file:
config_file.write(serial)
def write(self):
if self.show:
if self.errors != []:
if "tags" not in self.data:
self.data["tags"] = ["error"]
else:
self.data["tags"].append("error")
C = "+++\n"
C += toml.dumps(self.data)
C += "\n+++\n\n"
# C+=
C += self.content
dpath = j.sal.fs.joinPaths(self.docSite.outpath, "content", self.rpath)
j.sal.fs.createDir(j.sal.fs.getDirName(dpath))
j.sal.fs.writeFile(filename=dpath, contents=C)
# self.last_content = content
# self.last_path = self.path
# self.last_dest = j.sal.fs.joinPaths(j.sal.fs.getDirName(path), j.sal.fs.getBaseName(path)[1:])
# self.last_dest=j.sal.fs.joinPaths(self.root,j.sal.fs.pathRemoveDirPart(path,self.source))
# j.sal.fs.createDir(j.sal.fs.getDirName(self.last_dest))
# j.data.regex.replace(regexFind, regexFindsubsetToReplace, replaceWith, text)