本文整理汇总了Python中atomicwrites.atomic_write方法的典型用法代码示例。如果您正苦于以下问题:Python atomicwrites.atomic_write方法的具体用法?Python atomicwrites.atomic_write怎么用?Python atomicwrites.atomic_write使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类atomicwrites
的用法示例。
在下文中一共展示了atomicwrites.atomic_write方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: _write_pyc
# 需要导入模块: import atomicwrites [as 别名]
# 或者: from atomicwrites import atomic_write [as 别名]
def _write_pyc(state, co, source_stat, pyc):
# Technically, we don't have to have the same pyc format as
# (C)Python, since these "pycs" should never be seen by builtin
# import. However, there's little reason deviate.
try:
with atomicwrites.atomic_write(pyc, mode="wb", overwrite=True) as fp:
fp.write(importlib.util.MAGIC_NUMBER)
# as of now, bytecode header expects 32-bit numbers for size and mtime (#4903)
mtime = int(source_stat.st_mtime) & 0xFFFFFFFF
size = source_stat.st_size & 0xFFFFFFFF
# "<LL" stands for 2 unsigned longs, little-ending
fp.write(struct.pack("<LL", mtime, size))
fp.write(marshal.dumps(co))
except EnvironmentError as e:
state.trace("error writing pyc file at {}: errno={}".format(pyc, e.errno))
# we ignore any failure to write the cache file
# there are many reasons, permission-denied, __pycache__ being a
# file etc.
return False
return True
示例2: _write_pyc
# 需要导入模块: import atomicwrites [as 别名]
# 或者: from atomicwrites import atomic_write [as 别名]
def _write_pyc(
state: "AssertionState",
co: types.CodeType,
source_stat: os.stat_result,
pyc: Path,
) -> bool:
try:
with atomic_write(fspath(pyc), mode="wb", overwrite=True) as fp:
_write_pyc_fp(fp, source_stat, co)
except OSError as e:
state.trace("error writing pyc file at {}: {}".format(pyc, e))
# we ignore any failure to write the cache file
# there are many reasons, permission-denied, pycache dir being a
# file etc.
return False
return True
示例3: on_phrase
# 需要导入模块: import atomicwrites [as 别名]
# 或者: from atomicwrites import atomic_write [as 别名]
def on_phrase(j):
global LAST_COUNT
phrase = parse_phrase(j.get("phrase", []))
cmd = j["cmd"]
if cmd == "p.end":
if phrase:
with atomic_write(path, overwrite=True) as f:
f.write(phrase)
if WEBVIEW:
last_items.appendleft(phrase)
phrase_words = phrase.split()
if "history show" in phrase and phrase_words[-1].isdigit():
LAST_COUNT = int(phrase_words[-1])
webview.render(last_template, last_items=list(itertools.islice(last_items, 0, LAST_COUNT)))
if NOTIFY:
app.notify(body=phrase)
示例4: write_user_info
# 需要导入模块: import atomicwrites [as 别名]
# 或者: from atomicwrites import atomic_write [as 别名]
def write_user_info(self) -> None:
"""Write user info to a file."""
base_path = self.path()
if not base_path.exists():
base_path.mkdir()
with atomic_write(self.user_info_path, overwrite=True) as fp:
fp.write(
json.dumps(
{
"id_token": self.id_token,
"access_token": self.access_token,
"refresh_token": self.refresh_token,
},
indent=4,
)
)
self.user_info_path.chmod(0o600)
示例5: _finish_challenge
# 需要导入模块: import atomicwrites [as 别名]
# 或者: from atomicwrites import atomic_write [as 别名]
def _finish_challenge(self, handler: ChallengeHandler) -> None:
"""Wait until challenge is finished."""
_LOGGER.info("Finishing challenge for the new ACME certificate")
try:
self._acme_client.answer_challenge(handler.challenge, handler.response)
except errors.Error as err:
_LOGGER.error("Can't accept ACME challenge: %s", err)
raise AcmeChallengeError()
try:
order = self._acme_client.poll_and_finalize(handler.order)
except errors.Error as err:
_LOGGER.error("Wait of ACME challenge fails: %s", err)
raise AcmeChallengeError()
# Cleanup the old stuff
if self.path_fullchain.exists():
_LOGGER.info("Renew old certificate: %s", self.path_fullchain)
self.path_fullchain.unlink()
else:
_LOGGER.info("Create new certificate: %s", self.path_fullchain)
with atomic_write(self.path_fullchain, overwrite=True) as fp:
fp.write(order.fullchain_pem)
self.path_fullchain.chmod(0o600)
示例6: add
# 需要导入模块: import atomicwrites [as 别名]
# 或者: from atomicwrites import atomic_write [as 别名]
def add(self):
"""
Create a backup in <self.backup_directory>
"""
log = getLogger('ocrd.workspace_backup.add')
mets_str = self.workspace.mets.to_xml()
chksum = _chksum(mets_str)
backups = self.list()
if backups and backups[0].chksum == chksum:
log.info('No changes since last backup: %s' % backups[0])
else:
timestamp = datetime.now().timestamp()
d = join(self.backup_directory, '%s.%s' % (chksum, timestamp))
mets_file = join(d, 'mets.xml')
log.info("Backing up to %s" % mets_file)
makedirs(d)
with atomic_write(mets_file, overwrite=True) as f:
f.write(mets_str.decode('utf-8'))
return chksum
示例7: _set_alias
# 需要导入模块: import atomicwrites [as 别名]
# 或者: from atomicwrites import atomic_write [as 别名]
def _set_alias(self, alias, cap=None):
if not alias.endswith(":"):
alias = alias + ":"
aliases = self.get_aliases()
if cap:
aliases[alias] = cap
else:
try:
del aliases[alias]
except (KeyError, TypeError):
return
tmp_aliases_file = os.path.join(self.nodedir, "private", "aliases.tmp")
with atomic_write(tmp_aliases_file, mode="w", overwrite=True) as f:
data = ""
for name, dircap in aliases.items():
data += "{} {}\n".format(name, dircap)
f.write(data)
aliases_file = os.path.join(self.nodedir, "private", "aliases")
shutil.move(tmp_aliases_file, aliases_file)
示例8: _create_magic_folder
# 需要导入模块: import atomicwrites [as 别名]
# 或者: from atomicwrites import atomic_write [as 别名]
def _create_magic_folder(self, path, alias, poll_interval=60):
log.debug("Creating magic-folder for %s...", path)
admin_dircap = yield self.mkdir()
admin_dircap_json = yield self.get_json(admin_dircap)
collective_dircap = admin_dircap_json[1]["ro_uri"]
upload_dircap = yield self.mkdir()
upload_dircap_json = yield self.get_json(upload_dircap)
upload_dircap_ro = upload_dircap_json[1]["ro_uri"]
yield self.link(admin_dircap, "admin", upload_dircap_ro)
yaml_path = os.path.join(self.nodedir, "private", "magic_folders.yaml")
try:
with open(yaml_path) as f:
yaml_data = yaml.safe_load(f)
except OSError:
yaml_data = {}
folders_data = yaml_data.get("magic-folders", {})
folders_data[os.path.basename(path)] = {
"directory": path,
"collective_dircap": collective_dircap,
"upload_dircap": upload_dircap,
"poll_interval": poll_interval,
}
with atomic_write(yaml_path, mode="w", overwrite=True) as f:
f.write(yaml.safe_dump({"magic-folders": folders_data}))
self.add_alias(alias, admin_dircap)
示例9: export_to_file
# 需要导入模块: import atomicwrites [as 别名]
# 或者: from atomicwrites import atomic_write [as 别名]
def export_to_file(self):
dest, _ = QFileDialog.getSaveFileName(
self,
"Select a destination",
os.path.join(
os.path.expanduser("~"), APP_NAME + " Debug Information.txt"
),
)
if not dest:
return
try:
with atomic_write(dest, mode="w", overwrite=True) as f:
f.write(self.plaintextedit.toPlainText())
except Exception as e: # pylint: disable=broad-except
logging.error("%s: %s", type(e).__name__, str(e))
error(
self, "Error exporting debug information", str(e),
)
return
self.close()
示例10: ensure_recovery
# 需要导入模块: import atomicwrites [as 别名]
# 或者: from atomicwrites import atomic_write [as 别名]
def ensure_recovery(self, settings):
settings_path = os.path.join(
self.gateway.nodedir, "private", "settings.json"
)
if settings.get("rootcap"):
self.update_progress.emit("Loading Recovery Key...")
with atomic_write(
self.gateway.rootcap_path, mode="w", overwrite=True
) as f:
f.write(settings["rootcap"])
with atomic_write(settings_path, mode="w", overwrite=True) as f:
f.write(json.dumps(settings))
else:
self.update_progress.emit("Generating Recovery Key...")
try:
settings["rootcap"] = yield self.gateway.create_rootcap()
except OSError: # XXX Rootcap file already exists
pass
with atomic_write(settings_path, mode="w", overwrite=True) as f:
f.write(json.dumps(settings))
settings_cap = yield self.gateway.upload(settings_path)
yield self.gateway.link(
self.gateway.rootcap, "settings.json", settings_cap
)
示例11: save_documents
# 需要导入模块: import atomicwrites [as 别名]
# 或者: from atomicwrites import atomic_write [as 别名]
def save_documents(self):
if not os.path.exists(self.output_directory):
os.makedirs(self.output_directory)
claims_json = self.wait_for_claims_json()
downloads_needed = []
for claim in claims_json['claims']:
url = claim['eobLinkUrl']
pdf_path = os.path.join(self.output_directory,
claim['claimNumber'] + '.pdf')
json_path = os.path.join(self.output_directory,
claim['claimNumber'] + '.json')
if not os.path.exists(json_path):
with atomic_write(
json_path, mode='w', encoding='utf-8',
newline='\n') as f:
f.write(json.dumps(claim, indent=' ').strip() + '\n')
if not os.path.exists(pdf_path):
if not claim['eobLinkUrl'].startswith('https:/'): continue
downloads_needed.append((claim['eobLinkUrl'], pdf_path))
for i, (url, pdf_path) in enumerate(downloads_needed):
logger.info('Downloading EOB %d/%d', i + 1, len(downloads_needed))
self.driver.get(url)
download_result, = self.wait_and_return(self.get_downloaded_file)
with atomic_write(pdf_path, mode='wb') as f:
f.write(download_result[1])
示例12: test_atomic_write
# 需要导入模块: import atomicwrites [as 别名]
# 或者: from atomicwrites import atomic_write [as 别名]
def test_atomic_write(tmpdir):
fname = tmpdir.join('ha')
for i in range(2):
with atomic_write(str(fname), overwrite=True) as f:
f.write('hoho')
with pytest.raises(OSError) as excinfo:
with atomic_write(str(fname), overwrite=False) as f:
f.write('haha')
assert excinfo.value.errno == errno.EEXIST
assert fname.read() == 'hoho'
assert len(tmpdir.listdir()) == 1
示例13: test_teardown
# 需要导入模块: import atomicwrites [as 别名]
# 或者: from atomicwrites import atomic_write [as 别名]
def test_teardown(tmpdir):
fname = tmpdir.join('ha')
with pytest.raises(AssertionError):
with atomic_write(str(fname), overwrite=True):
assert False
assert not tmpdir.listdir()
示例14: test_replace_simultaneously_created_file
# 需要导入模块: import atomicwrites [as 别名]
# 或者: from atomicwrites import atomic_write [as 别名]
def test_replace_simultaneously_created_file(tmpdir):
fname = tmpdir.join('ha')
with atomic_write(str(fname), overwrite=True) as f:
f.write('hoho')
fname.write('harhar')
assert fname.read() == 'harhar'
assert fname.read() == 'hoho'
assert len(tmpdir.listdir()) == 1
示例15: test_dont_remove_simultaneously_created_file
# 需要导入模块: import atomicwrites [as 别名]
# 或者: from atomicwrites import atomic_write [as 别名]
def test_dont_remove_simultaneously_created_file(tmpdir):
fname = tmpdir.join('ha')
with pytest.raises(OSError) as excinfo:
with atomic_write(str(fname), overwrite=False) as f:
f.write('hoho')
fname.write('harhar')
assert fname.read() == 'harhar'
assert excinfo.value.errno == errno.EEXIST
assert fname.read() == 'harhar'
assert len(tmpdir.listdir()) == 1
# Verify that nested exceptions during rollback do not overwrite the initial
# exception that triggered a rollback.