本文整理汇总了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
示例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)
示例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.
示例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()
示例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()
示例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()
示例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)
示例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)
示例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()
示例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])
示例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
示例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)
示例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)
示例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])
示例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