本文整理汇总了Python中os.O_CREAT属性的典型用法代码示例。如果您正苦于以下问题:Python os.O_CREAT属性的具体用法?Python os.O_CREAT怎么用?Python os.O_CREAT使用的例子?那么恭喜您, 这里精选的属性代码示例或许可以为您提供帮助。您也可以进一步了解该属性所在类os
的用法示例。
在下文中一共展示了os.O_CREAT属性的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: write_pid_to_pidfile
# 需要导入模块: import os [as 别名]
# 或者: from os import O_CREAT [as 别名]
def write_pid_to_pidfile(pidfile_path):
""" Write the PID in the named PID file.
Get the numeric process ID (“PID”) of the current process
and write it to the named file as a line of text.
"""
open_flags = (os.O_CREAT | os.O_EXCL | os.O_WRONLY)
open_mode = 0o644
pidfile_fd = os.open(pidfile_path, open_flags, open_mode)
pidfile = os.fdopen(pidfile_fd, 'w')
# According to the FHS 2.3 section on PID files in /var/run:
#
# The file must consist of the process identifier in
# ASCII-encoded decimal, followed by a newline character. For
# example, if crond was process number 25, /var/run/crond.pid
# would contain three characters: two, five, and newline.
pid = os.getpid()
pidfile.write("%s\n" % pid)
pidfile.close()
示例2: writeToken
# 需要导入模块: import os [as 别名]
# 或者: from os import O_CREAT [as 别名]
def writeToken(self):
"""
Store details of the current connection in the named file.
This can be used by :meth:`readToken` to re-authenticate at a later time.
"""
# Write token file privately.
with os.fdopen(os.open(self.tokenFile, os.O_WRONLY | os.O_CREAT, 0o600), "w") as f:
# When opening files via os, truncation must be done manually.
f.truncate()
f.write(self.userId + "\n")
f.write(self.tokens["skype"] + "\n")
f.write(str(int(time.mktime(self.tokenExpiry["skype"].timetuple()))) + "\n")
f.write(self.tokens["reg"] + "\n")
f.write(str(int(time.mktime(self.tokenExpiry["reg"].timetuple()))) + "\n")
f.write(self.msgsHost + "\n")
示例3: create_cleanup_lock
# 需要导入模块: import os [as 别名]
# 或者: from os import O_CREAT [as 别名]
def create_cleanup_lock(p):
"""crates a lock to prevent premature folder cleanup"""
lock_path = get_lock_path(p)
try:
fd = os.open(str(lock_path), os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o644)
except OSError as e:
if e.errno == errno.EEXIST:
raise EnvironmentError(
"cannot create lockfile in {path}".format(path=p)
) from e
else:
raise
else:
pid = os.getpid()
spid = str(pid).encode()
os.write(fd, spid)
os.close(fd)
if not lock_path.is_file():
raise EnvironmentError("lock path got renamed after successful creation")
return lock_path
示例4: touch
# 需要导入模块: import os [as 别名]
# 或者: from os import O_CREAT [as 别名]
def touch(self, mode=0o666, exist_ok=True):
"""
Create this file with the given access mode, if it doesn't exist.
"""
if self._closed:
self._raise_closed()
if exist_ok:
# First try to bump modification time
# Implementation note: GNU touch uses the UTIME_NOW option of
# the utimensat() / futimens() functions.
try:
self._accessor.utime(self, None)
except OSError:
# Avoid exception chaining
pass
else:
return
flags = os.O_CREAT | os.O_WRONLY
if not exist_ok:
flags |= os.O_EXCL
fd = self._raw_open(flags, mode)
os.close(fd)
示例5: _init_dirs
# 需要导入模块: import os [as 别名]
# 或者: from os import O_CREAT [as 别名]
def _init_dirs(self):
test_dirs = ["a a", "b", "D_"]
config = "improbable"
root = tempfile.mkdtemp()
def cleanup():
try:
os.removedirs(root)
except (FileNotFoundError, OSError):
pass
os.chdir(root)
for dir_ in test_dirs:
os.mkdir(dir_, 0o0750)
f = "{0}.toml".format(config)
flags = os.O_WRONLY | os.O_CREAT
rel_path = "{0}/{1}".format(dir_, f)
abs_file_path = os.path.join(root, rel_path)
with os.fdopen(os.open(abs_file_path, flags, 0o0640), "w") as fp:
fp.write('key = "value is {0}"\n'.format(dir_))
return root, config, cleanup
示例6: store_acs_service_principal
# 需要导入模块: import os [as 别名]
# 或者: from os import O_CREAT [as 别名]
def store_acs_service_principal(subscription_id, client_secret, service_principal,
file_name='acsServicePrincipal.json'):
obj = {}
if client_secret:
obj['client_secret'] = client_secret
if service_principal:
obj['service_principal'] = service_principal
config_path = os.path.join(get_config_dir(), file_name)
full_config = load_service_principals(config_path=config_path)
if not full_config:
full_config = {}
full_config[subscription_id] = obj
with os.fdopen(os.open(config_path, os.O_RDWR | os.O_CREAT | os.O_TRUNC, 0o600),
'w+') as spFile:
json.dump(full_config, spFile)
示例7: test_usable_template
# 需要导入模块: import os [as 别名]
# 或者: from os import O_CREAT [as 别名]
def test_usable_template(self):
# gettempprefix returns a usable prefix string
# Create a temp directory, avoiding use of the prefix.
# Then attempt to create a file whose name is
# prefix + 'xxxxxx.xxx' in that directory.
p = tempfile.gettempprefix() + "xxxxxx.xxx"
d = tempfile.mkdtemp(prefix="")
try:
p = os.path.join(d, p)
try:
fd = os.open(p, os.O_RDWR | os.O_CREAT)
except:
self.failOnException("os.open")
os.close(fd)
os.unlink(p)
finally:
os.rmdir(d)
示例8: test_closerange
# 需要导入模块: import os [as 别名]
# 或者: from os import O_CREAT [as 别名]
def test_closerange(self):
first = os.open(test_support.TESTFN, os.O_CREAT|os.O_RDWR)
# We must allocate two consecutive file descriptors, otherwise
# it will mess up other file descriptors (perhaps even the three
# standard ones).
second = os.dup(first)
try:
retries = 0
while second != first + 1:
os.close(first)
retries += 1
if retries > 10:
# XXX test skipped
self.skipTest("couldn't allocate two consecutive fds")
first, second = second, os.dup(second)
finally:
os.close(second)
# close a fd that is open, and one that isn't
os.closerange(first, first + 2)
self.assertRaises(OSError, os.write, first, "a")
示例9: test_path_with_null_byte
# 需要导入模块: import os [as 别名]
# 或者: from os import O_CREAT [as 别名]
def test_path_with_null_byte(self):
fn = test_support.TESTFN
fn_with_NUL = fn + '\0'
self.addCleanup(test_support.unlink, fn)
test_support.unlink(fn)
fd = None
try:
with self.assertRaises(TypeError):
fd = os.open(fn_with_NUL, os.O_WRONLY | os.O_CREAT) # raises
finally:
if fd is not None:
os.close(fd)
self.assertFalse(os.path.exists(fn))
self.assertRaises(TypeError, os.mkdir, fn_with_NUL)
self.assertFalse(os.path.exists(fn))
open(fn, 'wb').close()
self.assertRaises(TypeError, os.stat, fn_with_NUL)
示例10: _test_single
# 需要导入模块: import os [as 别名]
# 或者: from os import O_CREAT [as 别名]
def _test_single(self, filename):
remove_if_exists(filename)
f = file(filename, "w")
f.close()
try:
self._do_single(filename)
finally:
os.unlink(filename)
self.assertTrue(not os.path.exists(filename))
# and again with os.open.
f = os.open(filename, os.O_CREAT)
os.close(f)
try:
self._do_single(filename)
finally:
os.unlink(filename)
示例11: test_write
# 需要导入模块: import os [as 别名]
# 或者: from os import O_CREAT [as 别名]
def test_write(self):
test_filename = "tmp.write.test"
# trivial write
fd = os.open(test_filename, flags)
self.assertEqual(os.write(fd, "42"), 2)
os.close(fd)
os.unlink(test_filename)
# write to closed file
fd = os.open(test_filename, flags)
os.close(fd)
self.assertRaisesMessage(OSError, "[Errno 9] Bad file descriptor", os.write, fd, "42")
os.unlink(test_filename)
# write to file with wrong permissions
fd = os.open(test_filename, os.O_CREAT | os.O_TRUNC | os.O_RDONLY)
self.assertRaisesMessage(OSError, "[Errno -2146232800] Can not write to " + test_filename, os.write, fd, "42")
os.close(fd)
os.unlink(test_filename)
示例12: redirect_io
# 需要导入模块: import os [as 别名]
# 或者: from os import O_CREAT [as 别名]
def redirect_io(log_file='/dev/null'):
# Always redirect stdin.
in_fd = os.open('/dev/null', os.O_RDONLY)
try:
os.dup2(in_fd, 0)
finally:
os.close(in_fd)
out_fd = os.open(log_file, os.O_WRONLY | os.O_CREAT)
try:
os.dup2(out_fd, 2)
os.dup2(out_fd, 1)
finally:
os.close(out_fd)
sys.stdin = os.fdopen(0, 'r')
sys.stdout = os.fdopen(1, 'w')
sys.stderr = os.fdopen(2, 'w')
示例13: upload_config
# 需要导入模块: import os [as 别名]
# 或者: from os import O_CREAT [as 别名]
def upload_config(self):
try:
stream = flask.request.stream
file_path = cfg.find_config_files(project=CONF.project,
prog=CONF.prog)[0]
flags = os.O_WRONLY | os.O_CREAT | os.O_TRUNC
# mode 00600
mode = stat.S_IRUSR | stat.S_IWUSR
with os.fdopen(os.open(file_path, flags, mode), 'wb') as cfg_file:
b = stream.read(BUFFER)
while b:
cfg_file.write(b)
b = stream.read(BUFFER)
CONF.mutate_config_files()
except Exception as e:
LOG.error("Unable to update amphora-agent configuration: "
"{}".format(str(e)))
return webob.Response(json=dict(
message="Unable to update amphora-agent configuration.",
details=str(e)), status=500)
return webob.Response(json={'message': 'OK'}, status=202)
示例14: install_netns_systemd_service
# 需要导入模块: import os [as 别名]
# 或者: from os import O_CREAT [as 别名]
def install_netns_systemd_service():
os_utils = osutils.BaseOS.get_os_util()
flags = os.O_WRONLY | os.O_CREAT | os.O_TRUNC
# mode 00644
mode = (stat.S_IRUSR | stat.S_IWUSR | stat.S_IRGRP | stat.S_IROTH)
# TODO(bcafarel): implement this for other init systems
# netns handling depends on a separate unit file
netns_path = os.path.join(consts.SYSTEMD_DIR,
consts.AMP_NETNS_SVC_PREFIX + '.service')
jinja_env = jinja2.Environment(
autoescape=True, loader=jinja2.FileSystemLoader(os.path.dirname(
os.path.realpath(__file__)
) + consts.AGENT_API_TEMPLATES))
if not os.path.exists(netns_path):
with os.fdopen(os.open(netns_path, flags, mode), 'w') as text_file:
text = jinja_env.get_template(
consts.AMP_NETNS_SVC_PREFIX + '.systemd.j2').render(
amphora_nsname=consts.AMPHORA_NAMESPACE,
HasIFUPAll=os_utils.has_ifup_all())
text_file.write(text)
示例15: upload_certificate
# 需要导入模块: import os [as 别名]
# 或者: from os import O_CREAT [as 别名]
def upload_certificate(self, lb_id, filename):
self._check_ssl_filename_format(filename)
# create directory if not already there
if not os.path.exists(self._cert_dir(lb_id)):
os.makedirs(self._cert_dir(lb_id))
stream = Wrapped(flask.request.stream)
file = self._cert_file_path(lb_id, filename)
flags = os.O_WRONLY | os.O_CREAT
# mode 00600
mode = stat.S_IRUSR | stat.S_IWUSR
with os.fdopen(os.open(file, flags, mode), 'wb') as crt_file:
b = stream.read(BUFFER)
while b:
crt_file.write(b)
b = stream.read(BUFFER)
resp = webob.Response(json=dict(message='OK'))
resp.headers['ETag'] = stream.get_md5()
return resp