Python os.O_CREAT Examples
The following are 30
code examples of os.O_CREAT().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
os
, or try the search function
.
Example #1
Source File: __init__.py From python-netsurv with MIT License | 6 votes |
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)
Example #2
Source File: test_posix.py From ironpython2 with Apache License 2.0 | 6 votes |
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)
Example #3
Source File: test_unicode_file.py From ironpython2 with Apache License 2.0 | 6 votes |
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)
Example #4
Source File: test_fd.py From ironpython2 with Apache License 2.0 | 6 votes |
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)
Example #5
Source File: __init__.py From python-netsurv with MIT License | 6 votes |
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)
Example #6
Source File: test_vyper.py From vyper with MIT License | 6 votes |
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
Example #7
Source File: test_tempfile.py From ironpython2 with Apache License 2.0 | 6 votes |
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)
Example #8
Source File: conn.py From SkPy with BSD 3-Clause "New" or "Revised" License | 6 votes |
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")
Example #9
Source File: parallel.py From avocado-vt with GNU General Public License v2.0 | 6 votes |
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')
Example #10
Source File: pidlockfile.py From Python24 with MIT License | 6 votes |
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()
Example #11
Source File: pathlib.py From python-netsurv with MIT License | 6 votes |
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
Example #12
Source File: pidlockfile.py From jbox with MIT License | 6 votes |
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()
Example #13
Source File: server.py From octavia with Apache License 2.0 | 6 votes |
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)
Example #14
Source File: util.py From octavia with Apache License 2.0 | 6 votes |
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)
Example #15
Source File: loadbalancer.py From octavia with Apache License 2.0 | 6 votes |
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
Example #16
Source File: test_os.py From ironpython2 with Apache License 2.0 | 6 votes |
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")
Example #17
Source File: pathlib.py From python-netsurv with MIT License | 6 votes |
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
Example #18
Source File: pidlockfile.py From recruit with Apache License 2.0 | 6 votes |
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()
Example #19
Source File: osutils.py From octavia with Apache License 2.0 | 6 votes |
def write_port_interface_file(self, netns_interface, fixed_ips, mtu, interface_file_path, template_port): # write interface file # If we are using a consolidated interfaces file, just append # otherwise clear the per interface file as we are rewriting it # TODO(johnsom): We need a way to clean out old interfaces records if CONF.amphora_agent.agent_server_network_file: flags = os.O_WRONLY | os.O_CREAT | os.O_APPEND else: 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 with os.fdopen(os.open(interface_file_path, flags, mode), 'w') as text_file: text = self._generate_network_file_text( netns_interface, fixed_ips, mtu, template_port) text_file.write(text)
Example #20
Source File: custom.py From azure-cli-extensions with MIT License | 6 votes |
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)
Example #21
Source File: plug.py From octavia with Apache License 2.0 | 5 votes |
def _update_plugged_interfaces_file(self, interface, mac_address): # write interfaces to plugged_interfaces file and prevent duplicates plug_inf_file = consts.PLUGGED_INTERFACES flags = os.O_RDWR | os.O_CREAT # mode 0644 mode = stat.S_IRUSR | stat.S_IWUSR | stat.S_IRGRP | stat.S_IROTH with os.fdopen(os.open(plug_inf_file, flags, mode), 'r+') as text_file: inf_list = [inf.split()[0].rstrip() for inf in text_file] if mac_address not in inf_list: text_file.write("{mac_address} {interface}\n".format( mac_address=mac_address, interface=interface))
Example #22
Source File: file_cache.py From Python24 with MIT License | 5 votes |
def _secure_open_write(filename, fmode): # We only want to write to this file, so open it in write only mode flags = os.O_WRONLY # os.O_CREAT | os.O_EXCL will fail if the file already exists, so we only # will open *new* files. # We specify this because we want to ensure that the mode we pass is the # mode of the file. flags |= os.O_CREAT | os.O_EXCL # Do not follow symlinks to prevent someone from making a symlink that # we follow and insecurely open a cache file. if hasattr(os, "O_NOFOLLOW"): flags |= os.O_NOFOLLOW # On Windows we'll mark this file as binary if hasattr(os, "O_BINARY"): flags |= os.O_BINARY # Before we open our file, we want to delete any existing file that is # there try: os.remove(filename) except (IOError, OSError): # The file must not exist already, so we can just skip ahead to opening pass # Open our file, the use of os.O_CREAT | os.O_EXCL will ensure that if a # race condition happens between the os.remove and this line, that an # error will be raised. Because we utilize a lockfile this should only # happen if someone is attempting to attack us. fd = os.open(filename, flags, fmode) try: return os.fdopen(fd, "wb") except: # An error occurred wrapping our FD in a file object os.close(fd) raise
Example #23
Source File: tarfile.py From ironpython2 with Apache License 2.0 | 5 votes |
def __init__(self, name, mode): mode = { "r": os.O_RDONLY, "w": os.O_WRONLY | os.O_CREAT | os.O_TRUNC, }[mode] if hasattr(os, "O_BINARY"): mode |= os.O_BINARY self.fd = os.open(name, mode, 0666)
Example #24
Source File: test_zipfile.py From ironpython2 with Apache License 2.0 | 5 votes |
def requiresWriteAccess(self, path): if not os.access(path, os.W_OK): self.skipTest('requires write access to the installed location') filename = os.path.join(path, 'test_zipfile.try') try: fd = os.open(filename, os.O_WRONLY | os.O_CREAT) os.close(fd) except Exception: self.skipTest('requires write access to the installed location') unlink(filename)
Example #25
Source File: test_gzip.py From ironpython2 with Apache License 2.0 | 5 votes |
def test_fileobj_from_io_open(self): fd = os.open(self.filename, os.O_WRONLY | os.O_CREAT) with io.open(fd, "wb") as f: with gzip.GzipFile(fileobj=f, mode="w") as g: self.assertEqual(g.name, "")
Example #26
Source File: test_gzip.py From ironpython2 with Apache License 2.0 | 5 votes |
def test_fileobj_from_fdopen(self): # Issue #13781: Creating a GzipFile using a fileobj from os.fdopen() # should not embed the fake filename "<fdopen>" in the output file. fd = os.open(self.filename, os.O_WRONLY | os.O_CREAT) with os.fdopen(fd, "wb") as f: with gzip.GzipFile(fileobj=f, mode="w") as g: self.assertEqual(g.name, "")
Example #27
Source File: test_zipimport.py From ironpython2 with Apache License 2.0 | 5 votes |
def testFileUnreadable(self): test_support.unlink(TESTMOD) fd = os.open(TESTMOD, os.O_CREAT, 000) try: os.close(fd) self.assertZipFailure(TESTMOD) finally: # If we leave "the read-only bit" set on Windows, nothing can # delete TESTMOD, and later tests suffer bogus failures. os.chmod(TESTMOD, 0666) test_support.unlink(TESTMOD)
Example #28
Source File: mailbox.py From ironpython2 with Apache License 2.0 | 5 votes |
def __init__(self, path, factory=None, create=True): """Initialize an MH instance.""" Mailbox.__init__(self, path, factory, create) if not os.path.exists(self._path): if create: os.mkdir(self._path, 0700) os.close(os.open(os.path.join(self._path, '.mh_sequences'), os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0600)) else: raise NoSuchMailboxError(self._path) self._locked = False
Example #29
Source File: mailbox.py From ironpython2 with Apache License 2.0 | 5 votes |
def add_folder(self, folder): """Create a folder and return a Maildir instance representing it.""" path = os.path.join(self._path, '.' + folder) result = Maildir(path, factory=self._factory) maildirfolder_path = os.path.join(path, 'maildirfolder') if not os.path.exists(maildirfolder_path): os.close(os.open(maildirfolder_path, os.O_CREAT | os.O_WRONLY, 0666)) return result
Example #30
Source File: support.py From jawfish with MIT License | 5 votes |
def create_empty_file(filename): """Create an empty file. If the file already exists, truncate it.""" fd = os.open(filename, os.O_WRONLY | os.O_CREAT | os.O_TRUNC) os.close(fd)