Python os.open() Examples
The following are 30
code examples of os.open().
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 |
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: terminalsize.py From asciidots with GNU Affero General Public License v3.0 | 7 votes |
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])
Example #3
Source File: factory-package-news.py From openSUSE-release-tools with GNU General Public License v2.0 | 6 votes |
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)
Example #4
Source File: workflow.py From Quiver-alfred with MIT License | 6 votes |
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
Example #5
Source File: interface.py From XFLTReaT with MIT License | 6 votes |
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 #6
Source File: pyfakewebcam.py From pyfakewebcam with GNU Lesser General Public License v3.0 | 6 votes |
def __init__(self, video_device, width, height, channels=3, input_pixfmt='RGB'): if channels != 3: raise NotImplementedError('Code only supports inputs with 3 channels right now. You tried to intialize with {} channels'.format(channels)) if input_pixfmt != 'RGB': raise NotImplementedError('Code only supports RGB pixfmt. You tried to intialize with {}'.format(input_pixfmt)) if not os.path.exists(video_device): sys.stderr.write('\n--- Make sure the v4l2loopback kernel module is loaded ---\n') sys.stderr.write('sudo modprobe v4l2loopback devices=1\n\n') raise FileNotFoundError('device does not exist: {}'.format(video_device)) self._channels = channels self._video_device = os.open(video_device, os.O_WRONLY | os.O_SYNC) self._settings = _v4l2.v4l2_format() self._settings.type = _v4l2.V4L2_BUF_TYPE_VIDEO_OUTPUT self._settings.fmt.pix.pixelformat = _v4l2.V4L2_PIX_FMT_YUYV self._settings.fmt.pix.width = width self._settings.fmt.pix.height = height self._settings.fmt.pix.field = _v4l2.V4L2_FIELD_NONE self._settings.fmt.pix.bytesperline = width * 2 self._settings.fmt.pix.sizeimage = width * height * 2 self._settings.fmt.pix.colorspace = _v4l2.V4L2_COLORSPACE_JPEG self._buffer = np.zeros((self._settings.fmt.pix.height, 2*self._settings.fmt.pix.width), dtype=np.uint8) self._yuv = np.zeros((self._settings.fmt.pix.height, self._settings.fmt.pix.width, 3), dtype=np.uint8) self._ones = np.ones((self._settings.fmt.pix.height, self._settings.fmt.pix.width, 1), dtype=np.uint8) self._rgb2yuv = np.array([[0.299, 0.587, 0.114, 0], [-0.168736, -0.331264, 0.5, 128], [0.5, -0.418688, -0.081312, 128]]) fcntl.ioctl(self._video_device, _v4l2.VIDIOC_S_FMT, self._settings)
Example #7
Source File: misc.py From rtp_cluster with BSD 2-Clause "Simplified" License | 6 votes |
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 #8
Source File: local.py From py with MIT License | 6 votes |
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()
Example #9
Source File: fbx2joints3d.py From 2D-Motion-Retargeting with MIT License | 6 votes |
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)
Example #10
Source File: capture.py From py with MIT License | 6 votes |
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()
Example #11
Source File: capture.py From py with MIT License | 6 votes |
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)
Example #12
Source File: userscripts.py From qutebrowser with GNU General Public License v3.0 | 6 votes |
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()
Example #13
Source File: programs.py From raveberry with GNU Lesser General Public License v3.0 | 6 votes |
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)
Example #14
Source File: workflow.py From Quiver-alfred with MIT License | 5 votes |
def open_workflowdir(self): """Open the workflow's :attr:`workflowdir` in Finder.""" subprocess.call(['open', self.workflowdir])
Example #15
Source File: workflow.py From Quiver-alfred with MIT License | 5 votes |
def load(cls, file_obj): """Load serialized object from open JSON file. .. versionadded:: 1.8 :param file_obj: file handle :type file_obj: ``file`` object :returns: object loaded from JSON file :rtype: object """ return json.load(file_obj)
Example #16
Source File: workflow.py From Quiver-alfred with MIT License | 5 votes |
def dump(cls, obj, file_obj): """Serialize object ``obj`` to open JSON file. .. versionadded:: 1.8 :param obj: Python object to serialize :type obj: JSON-serializable data structure :param file_obj: file handle :type file_obj: ``file`` object """ return json.dump(obj, file_obj, indent=2, encoding='utf-8')
Example #17
Source File: fbx2joints3d.py From 2D-Motion-Retargeting with MIT License | 5 votes |
def json2npy(): data_root = OUT_DATA_DIR character_names = os.listdir(data_root) print(character_names) total_num = 0 for char in character_names: char_dir = os.path.join(data_root, char) animation_names = os.listdir(char_dir) for anim in animation_names: joint_dir = os.path.join(char_dir, anim, 'jointsDict') nr_files = len(os.listdir(joint_dir)) motion = [] for i in range(0, nr_files): with open(os.path.join(joint_dir, '%04d_keypoints.json' % i)) as f: info = json.load(f) joint = np.array(info['pose_keypoints_3d']).reshape((-1, 3)) motion.append(joint[:15, :]) motion = np.stack(motion, axis=2) save_path = os.path.join(char_dir, anim, '{}.npy'.format(anim)) print(save_path) np.save(save_path, motion)
Example #18
Source File: workflow.py From Quiver-alfred with MIT License | 5 votes |
def open_datadir(self): """Open the workflow's :attr:`datadir` in Finder.""" subprocess.call(['open', self.datadir])
Example #19
Source File: factory-package-news.py From openSUSE-release-tools with GNU General Public License v2.0 | 5 votes |
def readRpmHeader(self, filename): """ Read an rpm header. """ fd = os.open(filename, os.O_RDONLY) h = self.readRpmHeaderFD(fd) os.close(fd) return h
Example #20
Source File: workflow.py From Quiver-alfred with MIT License | 5 votes |
def open_help(self): """Open :attr:`help_url` in default browser""" subprocess.call(['open', self.help_url]) return 'Opening workflow help URL in browser' #################################################################### # Helper methods ####################################################################
Example #21
Source File: event_storage_writer.py From thingsboard-gateway with Apache License 2.0 | 5 votes |
def create_file(self, prefix, filename): full_file_name = "%s%s.txt" % (prefix, filename) file_path = "%s%s" % (self.settings.get_data_folder_path(), full_file_name) try: file = os_open(file_path, O_CREAT | O_EXCL) os_close(file) return full_file_name except IOError as e: log.error("Failed to create a new file! Error: %s", e)
Example #22
Source File: workflow.py From Quiver-alfred with MIT License | 5 votes |
def acquire(self, blocking=True): """Acquire the lock if possible. If the lock is in use and ``blocking`` is ``False``, return ``False``. Otherwise, check every `self.delay` seconds until it acquires lock or exceeds `self.timeout` and raises an exception. """ start = time.time() while True: try: fd = os.open(self.lockfile, os.O_CREAT | os.O_EXCL | os.O_RDWR) with os.fdopen(fd, 'w') as fd: fd.write('{0}'.format(os.getpid())) break except OSError as err: if err.errno != errno.EEXIST: # pragma: no cover raise if self.timeout and (time.time() - start) >= self.timeout: raise AcquisitionError('Lock acquisition timed out.') if not blocking: return False time.sleep(self.delay) self._locked = True return True
Example #23
Source File: fusee-launcher.py From fusee-launcher with GNU General Public License v2.0 | 5 votes |
def _read_num_file(self, path): """ Reads a numeric value from a sysfs file that contains only a number. """ with open(path, 'r') as f: raw = f.read() return int(raw)
Example #24
Source File: __init__.py From dino with Apache License 2.0 | 5 votes |
def __init__(self): # Open a pair of null files self.null_fds = [os.open(os.devnull, os.O_RDWR) for _ in range(2)] # Save the actual stdout (1) and stderr (2) file descriptors. self.save_fds = (os.dup(1), os.dup(2))
Example #25
Source File: userscripts.py From qutebrowser with GNU General Public License v3.0 | 5 votes |
def __init__(self, filepath, parent=None): super().__init__(parent) self._filepath = filepath # We open as R/W so we never get EOF and have to reopen the pipe. # See http://www.outflux.net/blog/archives/2008/03/09/using-select-on-a-fifo/ # We also use os.open and os.fdopen rather than built-in open so we # can add O_NONBLOCK. # pylint: disable=no-member,useless-suppression fd = os.open(filepath, os.O_RDWR | os.O_NONBLOCK) # pylint: enable=no-member,useless-suppression self._fifo = os.fdopen(fd, 'r') self._notifier = QSocketNotifier(typing.cast(sip.voidptr, fd), QSocketNotifier.Read, self) self._notifier.activated.connect( # type: ignore[attr-defined] self.read_line)
Example #26
Source File: capture.py From py with MIT License | 5 votes |
def dupfile(f, mode=None, buffering=0, raising=False, encoding=None): """ return a new open file object that's a duplicate of f mode is duplicated if not given, 'buffering' controls buffer size (defaulting to no buffering) and 'raising' defines whether an exception is raised when an incompatible file object is passed in (if raising is False, the file object itself will be returned) """ try: fd = f.fileno() mode = mode or f.mode except AttributeError: if raising: raise return f newfd = os.dup(fd) if sys.version_info >= (3,0): if encoding is not None: mode = mode.replace("b", "") buffering = True return os.fdopen(newfd, mode, buffering, encoding, closefd=True) else: f = os.fdopen(newfd, mode, buffering) if encoding is not None: return EncodedFile(f, encoding) return f
Example #27
Source File: local.py From py with MIT License | 5 votes |
def copychunked(src, dest): chunksize = 524288 # half a meg of bytes fsrc = src.open('rb') try: fdest = dest.open('wb') try: while 1: buf = fsrc.read(chunksize) if not buf: break fdest.write(buf) finally: fdest.close() finally: fsrc.close()
Example #28
Source File: local.py From py with MIT License | 5 votes |
def ensure(self, *args, **kwargs): """ ensure that an args-joined path exists (by default as a file). if you specify a keyword argument 'dir=True' then the path is forced to be a directory path. """ p = self.join(*args) if kwargs.get('dir', 0): return p._ensuredirs() else: p.dirpath()._ensuredirs() if not p.check(file=1): p.open('w').close() return p
Example #29
Source File: local.py From py with MIT License | 5 votes |
def write_text(self, data, encoding, ensure=False): """ write text data into path using the specified encoding. If ensure is True create missing parent directories. """ if ensure: self.dirpath().ensure(dir=1) with self.open('w', encoding=encoding) as f: f.write(data)
Example #30
Source File: local.py From py with MIT License | 5 votes |
def write_binary(self, data, ensure=False): """ write binary data into path. If ensure is True create missing parent directories. """ if ensure: self.dirpath().ensure(dir=1) with self.open('wb') as f: f.write(data)