当前位置: 首页>>代码示例>>Python>>正文


Python os.open方法代码示例

本文整理汇总了Python中os.open方法的典型用法代码示例。如果您正苦于以下问题:Python os.open方法的具体用法?Python os.open怎么用?Python os.open使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在os的用法示例。


在下文中一共展示了os.open方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: freebsd_tun_alloc

# 需要导入模块: import os [as 别名]
# 或者: from os import open [as 别名]
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 
开发者ID:earthquake,项目名称:XFLTReaT,代码行数:23,代码来源:interface.py

示例2: daemonize

# 需要导入模块: import os [as 别名]
# 或者: from os import open [as 别名]
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) 
开发者ID:sippy,项目名称:rtp_cluster,代码行数:22,代码来源:misc.py

示例3: xzopen

# 需要导入模块: import os [as 别名]
# 或者: from os import open [as 别名]
def xzopen(cls, name, mode="r", fileobj=None, preset=None, **kwargs):
        """Open lzma compressed tar archive name for reading or writing.
           Appending is not allowed.
        """
        if mode not in ("r", "w"):
            raise ValueError("mode must be 'r' or 'w'")

        try:
            import lzma
        except ImportError:
            raise CompressionError("lzma module is not available")

        fileobj = lzma.LZMAFile(fileobj or name, mode, preset=preset)

        try:
            t = cls.taropen(name, mode, fileobj, **kwargs)
        except (lzma.LZMAError, EOFError):
            fileobj.close()
            raise ReadError("not an lzma file")
        t._extfileobj = False
        return t

    # All *open() methods are registered here. 
开发者ID:war-and-code,项目名称:jawfish,代码行数:25,代码来源:tarfile.py

示例4: __connect

# 需要导入模块: import os [as 别名]
# 或者: from os import open [as 别名]
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() 
开发者ID:notkarol,项目名称:derplearning,代码行数:18,代码来源:joystick.py

示例5: computehash

# 需要导入模块: import os [as 别名]
# 或者: from os import open [as 别名]
def computehash(self, hashtype="md5", chunksize=524288):
        """ return hexdigest of hashvalue for this file. """
        try:
            try:
                import hashlib as mod
            except ImportError:
                if hashtype == "sha1":
                    hashtype = "sha"
                mod = __import__(hashtype)
            hash = getattr(mod, hashtype)()
        except (AttributeError, ImportError):
            raise ValueError("Don't know how to compute %r hash" %(hashtype,))
        f = self.open('rb')
        try:
            while 1:
                buf = f.read(chunksize)
                if not buf:
                    return hash.hexdigest()
                hash.update(buf)
        finally:
            f.close() 
开发者ID:pytest-dev,项目名称:py,代码行数:23,代码来源:local.py

示例6: __init__

# 需要导入模块: import os [as 别名]
# 或者: from os import open [as 别名]
def __init__(self, targetfd, tmpfile=None, now=True, patchsys=False):
        """ save targetfd descriptor, and open a new
            temporary file there.  If no tmpfile is
            specified a tempfile.Tempfile() will be opened
            in text mode.
        """
        self.targetfd = targetfd
        if tmpfile is None and targetfd != 0:
            f = tempfile.TemporaryFile('wb+')
            tmpfile = dupfile(f, encoding="UTF-8")
            f.close()
        self.tmpfile = tmpfile
        self._savefd = os.dup(self.targetfd)
        if patchsys:
            self._oldsys = getattr(sys, patchsysdict[targetfd])
        if now:
            self.start() 
开发者ID:pytest-dev,项目名称:py,代码行数:19,代码来源:capture.py

示例7: start

# 需要导入模块: import os [as 别名]
# 或者: from os import open [as 别名]
def start(self):
        try:
            os.fstat(self._savefd)
        except OSError:
            raise ValueError("saved filedescriptor not valid, "
                "did you call start() twice?")
        if self.targetfd == 0 and not self.tmpfile:
            fd = os.open(devnullpath, os.O_RDONLY)
            os.dup2(fd, 0)
            os.close(fd)
            if hasattr(self, '_oldsys'):
                setattr(sys, patchsysdict[self.targetfd], DontReadFromInput())
        else:
            os.dup2(self.tmpfile.fileno(), self.targetfd)
            if hasattr(self, '_oldsys'):
                setattr(sys, patchsysdict[self.targetfd], self.tmpfile) 
开发者ID:pytest-dev,项目名称:py,代码行数:18,代码来源:capture.py

示例8: start

# 需要导入模块: import os [as 别名]
# 或者: from os import open [as 别名]
def start(self) -> None:
        self.current_frame = [0 for _ in range(self.bars)]
        self.growing_frame = b""
        try:
            # delete old contents of the pipe
            os.remove(self.cava_fifo_path)
        except FileNotFoundError:
            # the file does not exist
            pass
        try:
            os.mkfifo(self.cava_fifo_path)
        except FileExistsError:
            # the file already exists
            logging.info("%s already exists while starting", self.cava_fifo_path)

        self.cava_process = subprocess.Popen(
            ["cava", "-p", os.path.join(settings.BASE_DIR, "config/cava.config")],
            cwd=settings.BASE_DIR,
        )
        # cava_fifo = open(cava_fifo_path, 'r')
        self.cava_fifo = os.open(self.cava_fifo_path, os.O_RDONLY | os.O_NONBLOCK) 
开发者ID:raveberry,项目名称:raveberry,代码行数:23,代码来源:programs.py

示例9: _cleanup

# 需要导入模块: import os [as 别名]
# 或者: from os import open [as 别名]
def _cleanup(self):
        """Clean up temporary files after the userscript finished."""
        if self._cleaned_up:
            return
        assert self._filepath is not None

        try:
            with open(self._filepath, 'r', encoding='utf-8') as f:
                for line in f:
                    self.got_cmd.emit(line.rstrip())
        except OSError:
            log.procs.exception("Failed to read command file!")
        except UnicodeDecodeError as e:
            log.misc.error("Invalid unicode in userscript output: {}"
                           .format(e))

        super()._cleanup()
        self.finished.emit() 
开发者ID:qutebrowser,项目名称:qutebrowser,代码行数:20,代码来源:userscripts.py

示例10: _get_terminal_size_linux

# 需要导入模块: import os [as 别名]
# 或者: from os import open [as 别名]
def _get_terminal_size_linux():
    def ioctl_GWINSZ(fd):
        try:
            import fcntl
            import termios
            cr = struct.unpack('hh',
                               fcntl.ioctl(fd, termios.TIOCGWINSZ, '1234'))
            return cr
        except:
            pass
    cr = ioctl_GWINSZ(0) or ioctl_GWINSZ(1) or ioctl_GWINSZ(2)
    if not cr:
        try:
            fd = os.open(os.ctermid(), os.O_RDONLY)
            cr = ioctl_GWINSZ(fd)
            os.close(fd)
        except:
            pass
    if not cr:
        try:
            cr = (os.environ['LINES'], os.environ['COLUMNS'])
        except:
            return None
    return int(cr[1]), int(cr[0]) 
开发者ID:aaronjanse,项目名称:asciidots,代码行数:26,代码来源:terminalsize.py

示例11: atomic_writer

# 需要导入模块: import os [as 别名]
# 或者: from os import open [as 别名]
def atomic_writer(file_path, mode):
    """Atomic file writer.

    :param file_path: path of file to write to.
    :type file_path: ``unicode``
    :param mode: sames as for `func:open`
    :type mode: string

    .. versionadded:: 1.12

    Context manager that ensures the file is only written if the write
    succeeds. The data is first written to a temporary file.

    """
    temp_suffix = '.aw.temp'
    temp_file_path = file_path + temp_suffix
    with open(temp_file_path, mode) as file_obj:
        try:
            yield file_obj
            os.rename(temp_file_path, file_path)
        finally:
            try:
                os.remove(temp_file_path)
            except (OSError, IOError):
                pass 
开发者ID:danielecook,项目名称:Quiver-alfred,代码行数:27,代码来源:workflow.py

示例12: clear_scene_and_import_fbx

# 需要导入模块: import os [as 别名]
# 或者: from os import open [as 别名]
def clear_scene_and_import_fbx(filepath):
    """
    Clear the whole scene and import fbx file into the empty scene.

    :param filepath: filepath for fbx file
    """
    # redirect blender output info
    logfile = 'blender_render.log'
    open(logfile, 'w').close()
    old = os.dup(1)
    sys.stdout.flush()
    os.close(1)
    os.open(logfile, os.O_WRONLY)

    bpy.ops.wm.read_homefile(filepath=HOME_FILE_PATH)
    bpy.ops.import_scene.fbx(filepath=filepath)

    os.close(1)
    os.dup(old)
    os.close(old) 
开发者ID:ChrisWu1997,项目名称:2D-Motion-Retargeting,代码行数:22,代码来源:fbx2joints3d.py

示例13: do_save

# 需要导入模块: import os [as 别名]
# 或者: from os import open [as 别名]
def do_save(self, subcmd, opts, *dirs):
        """${cmd_name}: save changelog information for snapshot

        ${cmd_usage}
        ${cmd_option_list}
        """

        if not opts.dir:
            raise Exception("need --dir option")
        if not os.path.isdir(opts.dir):
            raise Exception("%s must be a directory" % opts.dir)
        if not opts.snapshot:
            raise Exception("missing snapshot option")

        f = open(os.path.join(opts.dir, opts.snapshot), 'wb')
        pickle.dump([data_version, self.readChangeLogs(dirs)], f) 
开发者ID:openSUSE,项目名称:openSUSE-release-tools,代码行数:18,代码来源:factory-package-news.py

示例14: _get_terminal_size_linux

# 需要导入模块: import os [as 别名]
# 或者: from os import open [as 别名]
def _get_terminal_size_linux(self):
        def ioctl_GWINSZ(fd):
            try:
                import fcntl
                import termios

                cr = struct.unpack("hh", fcntl.ioctl(fd, termios.TIOCGWINSZ, "1234"))
                return cr
            except:
                pass

        cr = ioctl_GWINSZ(0) or ioctl_GWINSZ(1) or ioctl_GWINSZ(2)
        if not cr:
            try:
                fd = os.open(os.ctermid(), os.O_RDONLY)
                cr = ioctl_GWINSZ(fd)
                os.close(fd)
            except:
                pass

        if not cr:
            try:
                cr = (os.environ["LINES"], os.environ["COLUMNS"])
            except:
                return None

        return int(cr[1]), int(cr[0]) 
开发者ID:sdispater,项目名称:clikit,代码行数:29,代码来源:terminal.py

示例15: lin_tun_alloc

# 需要导入模块: import os [as 别名]
# 或者: from os import open [as 别名]
def lin_tun_alloc(self, dev, flags):
		try:
			tun = os.open(Interface.LINUX_CLONEDEV, os.O_RDWR|os.O_NONBLOCK, 0)
			ifr = struct.pack('16sH', dev, flags)
			fcntl.ioctl(tun, self.IOCTL_LINUX_TUNSETIFF, ifr)

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

		return tun 
开发者ID:earthquake,项目名称:XFLTReaT,代码行数:13,代码来源:interface.py


注:本文中的os.open方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。