Python os.O_RDWR Examples

The following are 30 code examples of os.O_RDWR(). 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: joystick.py    From derplearning with MIT License 7 votes vote down vote up
def __connect(self):
        device_addr, hidraw_device, event_device = self.__find_device()
        if device_addr is None:
            return False
        self.__report_fd = os.open(hidraw_device, os.O_RDWR | os.O_NONBLOCK)
        self.__fd = FileIO(self.__report_fd, "rb+", closefd=False)
        self.__input_device = InputDevice(event_device)
        self.__input_device.grab()
        buf = bytearray(38)
        buf[0] = 0x02
        try:
            return bool(fcntl.ioctl(self.__fd, 3223734279, bytes(buf)))
        except:
            pass
        if self.recv():
            self.update_controller() 
Example #2
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 #3
Source File: pty.py    From BinderFilter with MIT License 6 votes vote down vote up
def slave_open(tty_name):
    """slave_open(tty_name) -> slave_fd
    Open the pty slave and acquire the controlling terminal, returning
    opened filedescriptor.
    Deprecated, use openpty() instead."""

    result = os.open(tty_name, os.O_RDWR)
    try:
        from fcntl import ioctl, I_PUSH
    except ImportError:
        return result
    try:
        ioctl(result, I_PUSH, "ptem")
        ioctl(result, I_PUSH, "ldterm")
    except IOError:
        pass
    return result 
Example #4
Source File: i2c.py    From python-periphery with MIT License 6 votes vote down vote up
def _open(self, devpath):
        # Open i2c device
        try:
            self._fd = os.open(devpath, os.O_RDWR)
        except OSError as e:
            raise I2CError(e.errno, "Opening I2C device: " + e.strerror)

        self._devpath = devpath

        # Query supported functions
        buf = array.array('I', [0])
        try:
            fcntl.ioctl(self._fd, I2C._I2C_IOC_FUNCS, buf, True)
        except (OSError, IOError) as e:
            self.close()
            raise I2CError(e.errno, "Querying supported functions: " + e.strerror)

        # Check that I2C_RDWR ioctl() is supported on this device
        if (buf[0] & I2C._I2C_FUNC_I2C) == 0:
            self.close()
            raise I2CError(None, "I2C not supported on device \"{:s}\"".format(devpath))

    # Methods 
Example #5
Source File: pty.py    From ironpython2 with Apache License 2.0 6 votes vote down vote up
def fork():
    """fork() -> (pid, master_fd)
    Fork and make the child a session leader with a controlling terminal."""

    try:
        pid, fd = os.forkpty()
    except (AttributeError, OSError):
        pass
    else:
        if pid == CHILD:
            try:
                os.setsid()
            except OSError:
                # os.forkpty() already set us session leader
                pass
        return pid, fd

    master_fd, slave_fd = openpty()
    pid = os.fork()
    if pid == CHILD:
        # Establish a new session.
        os.setsid()
        os.close(master_fd)

        # Slave becomes stdin/stdout/stderr of child.
        os.dup2(slave_fd, STDIN_FILENO)
        os.dup2(slave_fd, STDOUT_FILENO)
        os.dup2(slave_fd, STDERR_FILENO)
        if (slave_fd > STDERR_FILENO):
            os.close (slave_fd)

        # Explicitly open the tty to make it become a controlling tty.
        tmp_fd = os.open(os.ttyname(STDOUT_FILENO), os.O_RDWR)
        os.close(tmp_fd)
    else:
        os.close(slave_fd)

    # Parent and child process.
    return pid, master_fd 
Example #6
Source File: pty.py    From Computable with MIT License 6 votes vote down vote up
def slave_open(tty_name):
    """slave_open(tty_name) -> slave_fd
    Open the pty slave and acquire the controlling terminal, returning
    opened filedescriptor.
    Deprecated, use openpty() instead."""

    result = os.open(tty_name, os.O_RDWR)
    try:
        from fcntl import ioctl, I_PUSH
    except ImportError:
        return result
    try:
        ioctl(result, I_PUSH, "ptem")
        ioctl(result, I_PUSH, "ldterm")
    except IOError:
        pass
    return result 
Example #7
Source File: pty.py    From ironpython2 with Apache License 2.0 6 votes vote down vote up
def slave_open(tty_name):
    """slave_open(tty_name) -> slave_fd
    Open the pty slave and acquire the controlling terminal, returning
    opened filedescriptor.
    Deprecated, use openpty() instead."""

    result = os.open(tty_name, os.O_RDWR)
    try:
        from fcntl import ioctl, I_PUSH
    except ImportError:
        return result
    try:
        ioctl(result, I_PUSH, "ptem")
        ioctl(result, I_PUSH, "ldterm")
    except IOError:
        pass
    return result 
Example #8
Source File: pty.py    From oss-ftp with MIT License 6 votes vote down vote up
def slave_open(tty_name):
    """slave_open(tty_name) -> slave_fd
    Open the pty slave and acquire the controlling terminal, returning
    opened filedescriptor.
    Deprecated, use openpty() instead."""

    result = os.open(tty_name, os.O_RDWR)
    try:
        from fcntl import ioctl, I_PUSH
    except ImportError:
        return result
    try:
        ioctl(result, I_PUSH, "ptem")
        ioctl(result, I_PUSH, "ldterm")
    except IOError:
        pass
    return result 
Example #9
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 #10
Source File: virtio_console_guest.py    From avocado-vt with GNU General Public License v2.0 6 votes vote down vote up
def _open(self, in_files):
        """
        Open devices and return array of descriptors

        :param in_files: Files array
        :return: Array of descriptor
        """
        f = []

        for item in in_files:
            path = self.ports[item]["path"]
            if (path in self.files):
                f.append(self.files[path])
            else:
                try:
                    self.files[path] = os.open(path, os.O_RDWR)
                    if (self.ports[item]["is_console"] == "yes"):
                        print(os.system("stty -F %s raw -echo" % (path)))
                        print(os.system("stty -F %s -a" % (path)))
                    f.append(self.files[path])
                except Exception as inst:
                    print("FAIL: Failed to open file %s" % (path))
                    raise inst
        return f 
Example #11
Source File: virtio_console_guest.py    From avocado-vt with GNU General Public License v2.0 6 votes vote down vote up
def open(self, in_file, attempts=1):
        """
        Direct open devices.

        :param in_file: Array of files.
        :return: Array of descriptors.
        """
        opened = False
        for i in xrange(attempts):
            try:
                name = self.ports[in_file]["path"]
                self.files[name] = os.open(name, os.O_RDWR)
                if (self.ports[in_file]["is_console"] == "yes"):
                    print(os.system("stty -F %s raw -echo" % (name)))
                opened = True
                break
            except Exception as exc:
                print(str(exc))
                time.sleep(0.1)
        if opened:
            print("PASS: All files opened correctly. (%d)" % i)
        else:
            print("FAIL: Failed open file %s" % name) 
Example #12
Source File: pmsV3.py    From WebTools.bundle with Mozilla Public License 2.0 6 votes vote down vote up
def DelFromXML(self, fileName, attribute, value):
        Log.Debug('Need to delete element with an attribute named "%s" with a value of "%s" from file named "%s"' % (
            attribute, value, fileName))
        if Platform.OS == 'MacOSX':
            Log.Info('Mac OSx detected')
            try:
                xmlFile = os.fdopen(os.open(fileName, os.O_RDWR), "r+")
                with xmlFile as f:
                    tree = ElementTree.parse(f)
                    root = tree.getroot()
                    mySubtitles = root.findall('.//Subtitle')
                    for Subtitles in root.findall("Language[Subtitle]"):
                        for node in Subtitles.findall("Subtitle"):
                            myValue = node.attrib.get(attribute)
                            if myValue:
                                if '_' in myValue:
                                    drop, myValue = myValue.split("_")
                                if myValue == value:
                                    Subtitles.remove(node)
                    tree.write(f, encoding='utf-8', xml_declaration=True)
            except Exception, e:
                Log.Exception('Exception in DelFromXML was %s' % e) 
Example #13
Source File: misc.py    From rtp_cluster with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def daemonize(logfile = None):
    # Fork once
    if os.fork() != 0:
        os._exit(0)
    # Create new session
    os.setsid()
    if os.fork() != 0:
        os._exit(0)
    os.chdir('/')
    fd = os.open('/dev/null', os.O_RDWR)
    os.dup2(fd, sys.__stdin__.fileno())
    if logfile != None:
        fake_stdout = open(logfile, 'a', 1)
        sys.stdout = fake_stdout
        sys.stderr = fake_stdout
        fd = fake_stdout.fileno()
    os.dup2(fd, sys.__stdout__.fileno())
    os.dup2(fd, sys.__stderr__.fileno())
    if logfile == None:
        os.close(fd) 
Example #14
Source File: interface.py    From XFLTReaT with MIT License 6 votes vote down vote up
def freebsd_tun_alloc(self, dev, flags):
		try:
			sockfd = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
			ifr = struct.pack('<16si', 'tun', 0)
			self.iface_name = fcntl.ioctl(sockfd, self.IOCTL_FREEBSD_SIOCIFCREATE2, ifr)
			self.iface_name = self.iface_name.rstrip("\x00")

			buff = array.array('c', dev+"\x00")
			caddr_t, _ = buff.buffer_info()
			ifr = struct.pack('16sP', self.iface_name, caddr_t);

			fcntl.ioctl(sockfd, self.IOCTL_FREEBSD_SIOCSIFNAME, ifr)
			tun = os.open("/dev/"+self.iface_name, os.O_RDWR | os.O_NONBLOCK)
			self.iface_name = dev

		except IOError as e:
			print e
			common.internal_print("Error: Cannot create tunnel. Is {0} in use?".format(dev), -1)
			sys.exit(-1)

		return tun 
Example #15
Source File: getpass.py    From oss-ftp with MIT License 5 votes vote down vote up
def unix_getpass(prompt='Password: ', stream=None):
    """Prompt for a password, with echo turned off.

    Args:
      prompt: Written on stream to ask for the input.  Default: 'Password: '
      stream: A writable file object to display the prompt.  Defaults to
              the tty.  If no tty is available defaults to sys.stderr.
    Returns:
      The seKr3t input.
    Raises:
      EOFError: If our input tty or stdin was closed.
      GetPassWarning: When we were unable to turn echo off on the input.

    Always restores terminal settings before returning.
    """
    fd = None
    tty = None
    try:
        # Always try reading and writing directly on the tty first.
        fd = os.open('/dev/tty', os.O_RDWR|os.O_NOCTTY)
        tty = os.fdopen(fd, 'w+', 1)
        input = tty
        if not stream:
            stream = tty
    except EnvironmentError, e:
        # If that fails, see if stdin can be controlled.
        try:
            fd = sys.stdin.fileno()
        except (AttributeError, ValueError):
            passwd = fallback_getpass(prompt, stream)
        input = sys.stdin
        if not stream:
            stream = sys.stderr 
Example #16
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 #17
Source File: test_subprocess.py    From oss-ftp with MIT License 5 votes vote down vote up
def mkstemp():
        """Replacement for mkstemp, calling mktemp."""
        fname = tempfile.mktemp()
        return os.open(fname, os.O_RDWR|os.O_CREAT), fname 
Example #18
Source File: context_manager.py    From phocnet with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def __init__(self):
        # Open a pair of null files
        self.null_fds =  [os.open(os.devnull,os.O_RDWR) for x in range(2)]
        # Save the actual stdout (1) and stderr (2) file descriptors.
        self.save_fds = (os.dup(1), os.dup(2)) 
Example #19
Source File: pty.py    From BinderFilter with MIT License 5 votes vote down vote up
def fork():
    """fork() -> (pid, master_fd)
    Fork and make the child a session leader with a controlling terminal."""

    try:
        pid, fd = os.forkpty()
    except (AttributeError, OSError):
        pass
    else:
        if pid == CHILD:
            try:
                os.setsid()
            except OSError:
                # os.forkpty() already set us session leader
                pass
        return pid, fd

    master_fd, slave_fd = openpty()
    pid = os.fork()
    if pid == CHILD:
        # Establish a new session.
        os.setsid()
        os.close(master_fd)

        # Slave becomes stdin/stdout/stderr of child.
        os.dup2(slave_fd, STDIN_FILENO)
        os.dup2(slave_fd, STDOUT_FILENO)
        os.dup2(slave_fd, STDERR_FILENO)
        if (slave_fd > STDERR_FILENO):
            os.close (slave_fd)

        # Explicitly open the tty to make it become a controlling tty.
        tmp_fd = os.open(os.ttyname(STDOUT_FILENO), os.O_RDWR)
        os.close(tmp_fd)
    else:
        os.close(slave_fd)

    # Parent and child process.
    return pid, master_fd 
Example #20
Source File: http_utils.py    From clusterfuzz with Apache License 2.0 5 votes vote down vote up
def __enter__(self):
    self.stdout = os.dup(1)
    self.stderr = os.dup(2)
    os.close(1)
    os.close(2)
    os.open(os.devnull, os.O_RDWR) 
Example #21
Source File: mailbox.py    From oss-ftp with MIT License 5 votes vote down vote up
def _create_carefully(path):
    """Create a file if it doesn't exist and open for reading and writing."""
    fd = os.open(path, os.O_CREAT | os.O_EXCL | os.O_RDWR, 0666)
    try:
        return open(path, 'rb+')
    finally:
        os.close(fd) 
Example #22
Source File: pty.py    From BinderFilter with MIT License 5 votes vote down vote up
def _open_terminal():
    """Open pty master and return (master_fd, tty_name).
    SGI and generic BSD version, for when openpty() fails."""
    try:
        import sgi
    except ImportError:
        pass
    else:
        try:
            tty_name, master_fd = sgi._getpty(os.O_RDWR, 0666, 0)
        except IOError, msg:
            raise os.error, msg
        return master_fd, tty_name 
Example #23
Source File: print_tty.py    From aws-okta-processor with MIT License 5 votes vote down vote up
def unix_print_tty(string='', indents=0, newline=True):
    with contextlib2.ExitStack() as stack:
        string = indent(indents) + string
        fd = None

        try:
            # Always try reading and writing directly on the tty first.
            fd = os.open('/dev/tty', os.O_RDWR | os.O_NOCTTY)
            tty = io.FileIO(fd, 'w+')
            stack.enter_context(tty)
            text_input = io.TextIOWrapper(tty)
            stack.enter_context(text_input)
            stream = text_input
        except OSError:
            sys.stdout.write(string)

            if newline:
                sys.stdout.write('\n')

            stack.close()

        if fd is not None:
            try:
                stream.write(string)

                if newline:
                    stream.write('\n')
            finally:
                stream.flush() 
Example #24
Source File: lib.py    From edgedb with Apache License 2.0 5 votes vote down vote up
def redirect_stream(stream_name: str, target_stream: io.FileIO):
    """Redirect a system stream to the specified file.

    If ``target_stream`` is None - redirect to devnull.
    """
    if target_stream is None:
        target_fd = os.open(os.devnull, os.O_RDWR)
    else:
        target_fd = target_stream.fileno()

    system_stream = getattr(sys, stream_name)
    os.dup2(target_fd, system_stream.fileno())
    setattr(sys, '__{}__'.format(stream_name), system_stream) 
Example #25
Source File: ads111x.py    From PyCNC with MIT License 5 votes vote down vote up
def __init__(self):
        self._os_close = os.close
        # Initialize i2c interface and register it for closing on exit.
        self._dev = os.open("/dev/i2c-1", os.O_SYNC | os.O_RDWR)
        if self._dev < 0:
            raise ImportError("i2c device not found")
        else:
            if fcntl.ioctl(self._dev, I2C_SLAVE, ADS111x_ADDRESS) < 0:
                self._close()
                raise ImportError("Failed to set up i2c address")
            else:
                atexit.register(self._close) 
Example #26
Source File: rpgpio_private.py    From PyCNC with MIT License 5 votes vote down vote up
def _open_dev(name):
        fd = os.open(name, os.O_SYNC | os.O_RDWR)
        if fd < 0:
            raise IOError("Failed to open " + name)
        return fd 
Example #27
Source File: _pslinux.py    From psutil with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def file_flags_to_mode(flags):
    """Convert file's open() flags into a readable string.
    Used by Process.open_files().
    """
    modes_map = {os.O_RDONLY: 'r', os.O_WRONLY: 'w', os.O_RDWR: 'w+'}
    mode = modes_map[flags & (os.O_RDONLY | os.O_WRONLY | os.O_RDWR)]
    if flags & os.O_APPEND:
        mode = mode.replace('w', 'a', 1)
    mode = mode.replace('w+', 'r+')
    # possible values: r, w, a, r+, a+
    return mode 
Example #28
Source File: qemu.py    From grimoire with GNU Affero General Public License v3.0 5 votes vote down vote up
def init(self):
        self.control = safe_socket(socket.AF_UNIX)
        self.control.settimeout(None)
        self.control.setblocking(1)
        while True:
            try:
                self.control.connect(self.control_filename)
                # self.control.connect(self.control_filename)
                break
            except socket_error:
                pass
                # time.sleep(0.01)

        self.kafl_shm_f = os.open(self.bitmap_filename, os.O_RDWR | os.O_SYNC | os.O_CREAT)
        self.fs_shm_f = os.open(self.payload_filename, os.O_RDWR | os.O_SYNC | os.O_CREAT)

        open(self.tracedump_filename, "wb").close()

        os.symlink(self.tracedump_filename, self.config.argument_values['work_dir'] + "/pt_trace_dump_" + self.qemu_id)

        os.symlink(self.payload_filename, self.config.argument_values['work_dir'] + "/payload_" + self.qemu_id)
        os.symlink(self.bitmap_filename, self.config.argument_values['work_dir'] + "/bitmap_" + self.qemu_id)

        # argv_fd             = os.open(self.argv_filename, os.O_RDWR | os.O_SYNC | os.O_CREAT)
        os.ftruncate(self.kafl_shm_f, self.bitmap_size)
        os.ftruncate(self.fs_shm_f, (128 << 10))
        # os.ftruncate(argv_fd, (4 << 10))

        self.kafl_shm = mmap.mmap(self.kafl_shm_f, self.bitmap_size, mmap.MAP_SHARED, mmap.PROT_WRITE | mmap.PROT_READ)
        self.c_bitmap = (ctypes.c_uint8 * self.bitmap_size).from_buffer(self.kafl_shm)
        self.last_bitmap_wrapper = ExecutionResult(None, None, None, None)
        self.fs_shm = mmap.mmap(self.fs_shm_f, (128 << 10), mmap.MAP_SHARED, mmap.PROT_WRITE | mmap.PROT_READ)

        return True 
Example #29
Source File: bitmap.py    From grimoire with GNU Affero General Public License v3.0 5 votes vote down vote up
def create_bitmap(self, name):
        self.bitmap_fd = os.open(self.config.argument_values['work_dir'] + "/bitmaps/" + name,
                                 os.O_RDWR | os.O_SYNC | os.O_CREAT)
        os.ftruncate(self.bitmap_fd, self.config.config_values['BITMAP_SHM_SIZE'])
        self.bitmap = mmap.mmap(self.bitmap_fd, self.bitmap_size, mmap.MAP_SHARED, mmap.PROT_WRITE | mmap.PROT_READ) 
Example #30
Source File: mmio.py    From python-periphery with MIT License 5 votes vote down vote up
def _open(self, physaddr, size):
        if not isinstance(physaddr, (int, long)):
            raise TypeError("Invalid physaddr type, should be integer.")
        if not isinstance(size, (int, long)):
            raise TypeError("Invalid size type, should be integer.")

        pagesize = os.sysconf(os.sysconf_names['SC_PAGESIZE'])

        self._physaddr = physaddr
        self._size = size
        self._aligned_physaddr = physaddr - (physaddr % pagesize)
        self._aligned_size = size + (physaddr - self._aligned_physaddr)

        try:
            fd = os.open("/dev/mem", os.O_RDWR | os.O_SYNC)
        except OSError as e:
            raise MMIOError(e.errno, "Opening /dev/mem: " + e.strerror)

        try:
            self.mapping = mmap.mmap(fd, self._aligned_size, flags=mmap.MAP_SHARED, prot=(mmap.PROT_READ | mmap.PROT_WRITE), offset=self._aligned_physaddr)
        except OSError as e:
            raise MMIOError(e.errno, "Mapping /dev/mem: " + e.strerror)

        try:
            os.close(fd)
        except OSError as e:
            raise MMIOError(e.errno, "Closing /dev/mem: " + e.strerror)

    # Methods