Python os.O_TRUNC Examples

The following are 30 code examples of os.O_TRUNC(). 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: config.py    From renku-python with Apache License 2.0 6 votes vote down vote up
def store_config(self, config, global_only):
        """Persists locally or globally configuration object.

        Global configuration is updated only when :global_only: is True,
        otherwise, updates are written to local project configuration
        """
        filepath = self.global_config_path if global_only else \
            self.local_config_path

        if global_only:
            os.umask(0)
            fd = os.open(filepath, os.O_CREAT | os.O_RDWR | os.O_TRUNC, 0o600)
            with self.global_config_lock:
                with open(fd, 'w+') as file:
                    config.write(file)
        else:
            with open(filepath, 'w+') as file:
                config.write(file)

        return self.load_config(local_only=True, global_only=True) 
Example #2
Source File: server.py    From octavia with Apache License 2.0 6 votes vote down vote up
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 #3
Source File: test_fd.py    From ironpython2 with Apache License 2.0 6 votes vote down vote up
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 #4
Source File: util.py    From octavia with Apache License 2.0 6 votes vote down vote up
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 #5
Source File: mailbox.py    From Fluid-Designer with GNU General Public License v3.0 6 votes vote down vote up
def __setitem__(self, key, message):
        """Replace the keyed message; raise KeyError if it doesn't exist."""
        path = os.path.join(self._path, str(key))
        try:
            f = open(path, 'rb+')
        except OSError as e:
            if e.errno == errno.ENOENT:
                raise KeyError('No message with key: %s' % key)
            else:
                raise
        try:
            if self._locked:
                _lock_file(f)
            try:
                os.close(os.open(path, os.O_WRONLY | os.O_TRUNC))
                self._dump_message(message, f)
                if isinstance(message, MHMessage):
                    self._dump_sequences(message, key)
            finally:
                if self._locked:
                    _unlock_file(f)
        finally:
            _sync_close(f) 
Example #6
Source File: isolate.py    From judge-server with GNU Affero General Public License v3.0 6 votes vote down vote up
def is_write_flags(self, open_flags):
        for flag in [os.O_WRONLY, os.O_RDWR, os.O_TRUNC, os.O_CREAT, os.O_EXCL, os.O_TMPFILE]:
            # Strict equality is necessary here, since e.g. O_TMPFILE has multiple bits set,
            # and O_DIRECTORY & O_TMPFILE > 0.
            if open_flags & flag == flag:
                return True

        return False 
Example #7
Source File: osutils.py    From octavia with Apache License 2.0 6 votes vote down vote up
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 #8
Source File: custom.py    From azure-cli-extensions with MIT License 6 votes vote down vote up
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 #9
Source File: tarfile.py    From pipenv with MIT License 5 votes vote down vote up
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, 0o666) 
Example #10
Source File: server.py    From pysftpserver with MIT License 5 votes vote down vote up
def new_handle(self, filename, flags=0, attrs=dict(), is_opendir=False):
        if is_opendir:
            handle = self.storage.opendir(filename)
        else:
            os_flags = 0x00000000
            if flags & SSH2_FXF_READ and flags & SSH2_FXF_WRITE:
                os_flags |= os.O_RDWR
            elif flags & SSH2_FXF_READ:
                os_flags |= os.O_RDONLY
            elif flags & SSH2_FXF_WRITE:
                os_flags |= os.O_WRONLY
            if flags & SSH2_FXF_APPEND:
                os_flags |= os.O_APPEND
            if flags & SSH2_FXF_CREAT:
                os_flags |= os.O_CREAT
            if flags & SSH2_FXF_TRUNC and flags & SSH2_FXF_CREAT:
                os_flags |= os.O_TRUNC
            if flags & SSH2_FXF_EXCL and flags & SSH2_FXF_CREAT:
                os_flags |= os.O_EXCL
            mode = attrs.get(b'perm', 0o666)
            handle = self.storage.open(filename, os_flags, mode)
        if self.handle_cnt == 0xffffffffffffffff:
            raise OverflowError()
        self.handle_cnt += 1
        handle_id = bytes(self.handle_cnt)
        self.handles[handle_id] = handle
        if is_opendir:
            self.dirs[handle_id] = filename
        else:
            self.files[handle_id] = filename
        return handle_id 
Example #11
Source File: proxystorage.py    From pysftpserver with MIT License 5 votes vote down vote up
def flags_to_mode(flags, mode):
        """Convert:
            os module flags and mode -> Paramiko file open mode.
        Note: mode is ignored ATM.
        """
        paramiko_mode = ''
        if flags & os.O_WRONLY or (flags & os.O_WRONLY and flags & os.O_TRUNC):
            paramiko_mode = 'w'
        elif flags & os.O_RDWR and flags & os.O_APPEND:
            paramiko_mode = 'a+'
        elif flags & os.O_RDWR and flags & os.O_CREAT:
            paramiko_mode = 'w+'
        elif flags & os.O_APPEND:
            paramiko_mode = 'a'
        elif flags & os.O_RDWR and flags & os.O_TRUNC:
            paramiko_mode = 'w+'
        elif flags & os.O_RDWR:
            paramiko_mode = 'r+'
        elif flags & os.O_CREAT:
            paramiko_mode = 'w'
        else:  # OS.O_RDONLY fallback to read
            paramiko_mode = 'r'

        if flags & os.O_CREAT and flags & os.O_EXCL:
            paramiko_mode += 'x'

        return paramiko_mode 
Example #12
Source File: tarfile.py    From deepWordBug with Apache License 2.0 5 votes vote down vote up
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, 0o666) 
Example #13
Source File: tarfile.py    From pipenv with MIT License 5 votes vote down vote up
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, 0o666) 
Example #14
Source File: read_only.py    From gitfs with Apache License 2.0 5 votes vote down vote up
def open(self, path, flags):
        write_flags = os.O_WRONLY | os.O_RDWR | os.O_APPEND | os.O_TRUNC | os.O_CREAT

        if write_flags & flags:
            raise FuseOSError(EROFS)

        return 0 
Example #15
Source File: mailbox.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
def set_sequences(self, sequences):
        """Set sequences using the given name-to-key-list dictionary."""
        f = open(os.path.join(self._path, '.mh_sequences'), 'r+', encoding='ASCII')
        try:
            os.close(os.open(f.name, os.O_WRONLY | os.O_TRUNC))
            for name, keys in sequences.items():
                if len(keys) == 0:
                    continue
                f.write(name + ':')
                prev = None
                completing = False
                for key in sorted(set(keys)):
                    if key - 1 == prev:
                        if not completing:
                            completing = True
                            f.write('-')
                    elif completing:
                        completing = False
                        f.write('%s %s' % (prev, key))
                    else:
                        f.write(' %s' % key)
                    prev = key
                if completing:
                    f.write(str(prev) + '\n')
                else:
                    f.write('\n')
        finally:
            _sync_close(f) 
Example #16
Source File: tarfile.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
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, 0o666) 
Example #17
Source File: __init__.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
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) 
Example #18
Source File: time-machine.py    From rsync-time-machine with GNU General Public License v2.0 5 votes vote down vote up
def flock_exclusive():
    ''' lock so only one snapshot of current config is running '''
    fd = os.open(cfg['lock_file'], os.O_CREAT | os.O_TRUNC | os.O_WRONLY, 0600)
    try:
        fcntl.lockf(fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
    except IOError:
        return False
    return fd 
Example #19
Source File: support.py    From deepWordBug with Apache License 2.0 5 votes vote down vote up
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) 
Example #20
Source File: tarfile.py    From GraphicDesignPatternByPython with MIT License 5 votes vote down vote up
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, 0o666) 
Example #21
Source File: tarfile.py    From pex with Apache License 2.0 5 votes vote down vote up
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, 0o666) 
Example #22
Source File: unix.py    From Safejumper-for-Desktop with GNU General Public License v2.0 5 votes vote down vote up
def __init__(self, server, filename, flags, attrs):
        self.server = server
        openFlags = 0
        if flags & FXF_READ == FXF_READ and flags & FXF_WRITE == 0:
            openFlags = os.O_RDONLY
        if flags & FXF_WRITE == FXF_WRITE and flags & FXF_READ == 0:
            openFlags = os.O_WRONLY
        if flags & FXF_WRITE == FXF_WRITE and flags & FXF_READ == FXF_READ:
            openFlags = os.O_RDWR
        if flags & FXF_APPEND == FXF_APPEND:
            openFlags |= os.O_APPEND
        if flags & FXF_CREAT == FXF_CREAT:
            openFlags |= os.O_CREAT
        if flags & FXF_TRUNC == FXF_TRUNC:
            openFlags |= os.O_TRUNC
        if flags & FXF_EXCL == FXF_EXCL:
            openFlags |= os.O_EXCL
        if "permissions" in attrs:
            mode = attrs["permissions"]
            del attrs["permissions"]
        else:
            mode = 0o777
        fd = server.avatar._runAsUser(os.open, filename, openFlags, mode)
        if attrs:
            server.avatar._runAsUser(server._setAttrs, filename, attrs)
        self.fd = fd 
Example #23
Source File: tarfile.py    From Safejumper-for-Desktop with GNU General Public License v2.0 5 votes vote down vote up
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, 0o666) 
Example #24
Source File: tarfile.py    From anpr with Creative Commons Attribution 4.0 International 5 votes vote down vote up
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, 0o666) 
Example #25
Source File: tarfile.py    From Mastering-Elasticsearch-7.0 with MIT License 5 votes vote down vote up
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, 0o666) 
Example #26
Source File: tarfile.py    From Mastering-Elasticsearch-7.0 with MIT License 5 votes vote down vote up
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, 0o666) 
Example #27
Source File: config.py    From aeios with MIT License 5 votes vote down vote up
def _acquire(self):
        """
        Unix based locking using fcntl.flock(LOCK_EX | LOCK_NB)
        """
        flags = os.O_RDWR | os.O_CREAT | os.O_TRUNC
        fd = os.open(self._file, flags, 0644)
        try:
            fcntl.flock(fd, fcntl.LOCK_EX|fcntl.LOCK_NB)
            self._fd = fd
        except (IOError, OSError):
            os.close(fd) 
Example #28
Source File: mailbox.py    From oss-ftp with MIT License 5 votes vote down vote up
def set_sequences(self, sequences):
        """Set sequences using the given name-to-key-list dictionary."""
        f = open(os.path.join(self._path, '.mh_sequences'), 'r+')
        try:
            os.close(os.open(f.name, os.O_WRONLY | os.O_TRUNC))
            for name, keys in sequences.iteritems():
                if len(keys) == 0:
                    continue
                f.write('%s:' % name)
                prev = None
                completing = False
                for key in sorted(set(keys)):
                    if key - 1 == prev:
                        if not completing:
                            completing = True
                            f.write('-')
                    elif completing:
                        completing = False
                        f.write('%s %s' % (prev, key))
                    else:
                        f.write(' %s' % key)
                    prev = key
                if completing:
                    f.write(str(prev) + '\n')
                else:
                    f.write('\n')
        finally:
            _sync_close(f) 
Example #29
Source File: tarfile.py    From oss-ftp with MIT License 5 votes vote down vote up
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 #30
Source File: tarfile.py    From oss-ftp with MIT License 5 votes vote down vote up
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, 0o666)