def generateMediaInfo(filename, log=config.mi_debug, template=config.mi_config, environment=environ, buf=config.mi_tmpfile_size, tmpLoc=config.mi_tmpfile): """ Calls MediaInfo to generate metadata with a template :param: filename (Full Access path to file) :return: Temp File Name generated by MediaInfo """ template_string = "--Inform=file://" + template filename_wo_extn = path.splitext(path.basename(filename))[0] mi_filename = path.join(tmpLoc, filename_wo_extn + '.txt') command = [config.mi_exec, template_string, filename] fileno_out = os_open(mi_filename, O_RDWR | O_CREAT) if log: fileno_err = os_open(path.join(tmpLoc, filename_wo_extn + '_err.txt' ), O_RDWR | O_CREAT) fp_out = fdopen(fileno_out, 'r+b') if log: fp_err = fdopen(fileno_err, 'r+b') p = subprocess.Popen(command, stdout=fp_out, stderr=fp_err, env=environment) else: p = subprocess.Popen(command, stdout=fp_out, stderr=None, env=environment) p.wait() fp_out.seek(0) #x = os_read(fileno_out,buf) fp_out.close() if log: fp_err.close() return mi_filename
def _handle_execute(execute_file, execute_args, stdin_file, stdout_file, stderr_file, extra_file, cgroup_file): pid = fork() if not pid: chdir('/in/package') if stdin_file: fd = os_open(stdin_file, O_RDONLY) dup2(fd, STDIN_FILENO) os_close(fd) if stdout_file: fd = os_open(stdout_file, O_WRONLY) dup2(fd, STDOUT_FILENO) os_close(fd) if stderr_file: fd = os_open(stderr_file, O_WRONLY) dup2(fd, STDERR_FILENO) os_close(fd) if extra_file: fd = os_open(extra_file, O_RDONLY) if fd == EXTRA_FILENO: set_inheritable(fd, True) else: dup2(fd, EXTRA_FILENO) os_close(fd) if cgroup_file: enter_cgroup(cgroup_file) execve(execute_file, execute_args, SPAWN_ENV) return wait_and_reap_zombies(pid)
def init(self): frontfile = self.frontfile self.front_fd = os_open(frontfile, O_RDWR | O_CREAT | O_APPEND, 0o600) backfile = self.backfile self.back_fd = os_open(backfile, O_RDWR | O_CREAT | O_APPEND, 0o600) self._pid = getpid() del self.get_output del self.get_input
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: os_open(file_path, O_CREAT | O_EXCL) return full_file_name except IOError as e: log.error("Failed to create a new file!", e)
def do_build(self, stdin_file, stdout_file, stderr_file, cgroup_file): pid = fork() if not pid: chdir('/out') if stdin_file: dup2(os_open(stdin_file, O_RDONLY), STDIN_FILENO) if stdout_file: dup2(os_open(stdout_file, O_WRONLY), STDOUT_FILENO) if stderr_file: dup2(os_open(stderr_file, O_WRONLY), STDERR_FILENO) if cgroup_file: enter_cgroup(cgroup_file) execve(self.compiler_file, self.compiler_args, SPAWN_ENV) return wait_and_reap_zombies(pid)
def time_subprocess(command, output_limit, time_limit, input_file): global timed_out, timing_pid errfile, errfilename = tempfile.mkstemp() piper, pipew = pipe() set_inheritable(pipew, True) set_inheritable(piper, False) timed_out = False timing_pid = fork() t1 = resource.getrusage(resource.RUSAGE_CHILDREN) t1 = t1.ru_utime + t1.ru_stime if (timing_pid == 0): dup2(pipew, STDOUT_FILENO) dup2(os_open(input_file, O_RDONLY), STDIN_FILENO) if config["error_file"] != None: dup2(os_open(config["error_file"], O_WRONLY), STDERR_FILENO) else: dup2(errfile, STDERR_FILENO) close(pipew) # usage = resource.getrusage(resource.RUSAGE_SELF) # write(STDOUT_FILENO, (str(usage.ru_utime+usage.ru_stime)+"\n").encode("utf-8")) signal.setitimer(signal.ITIMER_VIRTUAL, time_limit) execv("/bin/sh", ["sh", "-c", command]) print("Couldn't run executable") elif timing_pid == -1: print("Could not create child process!") else: dup2(piper, STDIN_FILENO) # t1 += float(sys.stdin.readline()) # signal.setitimer(signal.ITIMER_VIRTUAL, time_limit) pid, rv = wait() if rv == 26: timed_out = True close(errfile) with open(errfilename, "r") as f: errstring = f.read() rm(errfilename) t2 = resource.getrusage(resource.RUSAGE_CHILDREN) t2 = t2.ru_utime + t2.ru_stime close(piper) close(pipew) result = StringIO() i = 0 line = sys.stdin.readline() while (i < output_limit and line != ""): result.write(line) line = sys.stdin.readline() i += 1 return (t2 - t1, result.getvalue(), rv, errstring)
def setDelay(self, device, value): #REP_DELAY if self.getDeviceAttribute(device, 'enabled') == True: print "[iInputDevices] setDelay for device %s to %d ms" % (device,value) event = struct.pack('iihhi', 0, 0, 0x14, 0x00, int(value)) fd = os_open("/dev/input/" + device, O_RDWR) os_write(fd, event) os_close(fd)
def setRepeat(self, device, value): #REP_PERIOD if self.getDeviceAttribute(device, 'enabled'): print("[InputDevice] setRepeat for device %s to %d ms" % (device, value)) event = struct.pack('LLHHi', 0, 0, 0x14, 0x01, int(value)) fd = os_open("/dev/input/" + device, O_RDWR) write(fd, event) close(fd)
def _get_terminal_size_linux(): def ioctl_GWINSZ(fd): try: from fcntl import ioctl as fcntl_ioctl 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: from os import ctermid as os_ctermid 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])
def save(self, content): makedirs(paths.jupyter_config_dir(), exist_ok=True) with fdopen(os_open(self.__config_path, O_RDWR | O_CREAT, 0o600), 'w+') as json_file: json_file.seek(0) json_file.truncate() json_file.write( json.dumps(self.__dict_merge(self.__default_config.copy(), content), indent=2, sort_keys=True))
def getInputDevices(self): devices = listdir("/dev/input/") for evdev in devices: try: buffer = "\0" * 512 self.fd = os_open("/dev/input/" + evdev, O_RDWR | O_NONBLOCK) self.name = ioctl(self.fd, EVIOCGNAME(256), buffer) self.name = self.name[:self.name.find("\0")] if str(self.name).find("Keyboard") != -1: self.name = 'keyboard' os_close(self.fd) except (IOError, OSError), err: print '[iInputDevices] getInputDevices <ERROR: ioctl(EVIOCGNAME): ' + str( err) + ' >' self.name = None if self.name: self.Devices[evdev] = { 'name': self.name, 'type': self.getInputDeviceType(self.name), 'enabled': False, 'configuredName': None } if getBoxType().startswith('et'): self.setDefaults( evdev ) # load default remote control "delay" and "repeat" values for ETxxxx ("QuickFix Scrollspeed Menues" proposed by Xtrend Support)
def match_or_trust(self, host, der_encoded_certificate): base64_encoded_certificate = b64encode(der_encoded_certificate) if isfile(self.path): with open(self.path) as f_in: for line in f_in: known_host, _, known_cert = line.strip().partition(":") known_cert = known_cert.encode("utf-8") if host == known_host: return base64_encoded_certificate == known_cert # First use (no hosts match) try: makedirs(dirname(self.path)) except OSError: pass f_out = os_open(self.path, O_CREAT | O_APPEND | O_WRONLY, 0o600) # TODO: Windows if isinstance(host, bytes): os_write(f_out, host) else: os_write(f_out, host.encode("utf-8")) os_write(f_out, b":") os_write(f_out, base64_encoded_certificate) os_write(f_out, b"\n") os_close(f_out) return True
def getInputDevices(self): for evdev in sorted(listdir("/dev/input")): try: fd = os_open("/dev/input/%s" % evdev, O_RDONLY | O_CLOEXEC) except: continue buf = "\0"*256 try: size = ioctl(fd, EVIOCGNAME(len(buf)), buf) except: os_close(fd) continue os_close(fd) if size <= 0: continue name = buf[:size - 1] if name: if name == "dreambox advanced remote control (native)" and config.misc.rcused.value not in (0, 2): continue if name == "dreambox remote control (native)" and config.misc.rcused.value in (0, 2): continue if name == "dreambox front panel": continue self.Devices[evdev] = {'name': name, 'type': self.getInputDeviceType(name),'enabled': False, 'configuredName': None }
def render_POST(self, req): req.setResponseCode(http.OK) req.setHeader('Content-type', 'application/xhtml+xml;' ) req.setHeader('charset', 'UTF-8') data = req.args['file'][0] if not data: result = """<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n <e2simplexmlresult>\n <e2state>False</e2state> <e2statetext>Filesize was 0, not uploaded</e2statetext> </e2simplexmlresult>\n""" return result fd = os_open( self.FILENAME, os_O_WRONLY|os_O_CREAT ) if fd: cnt = os_write(fd, data) os_close(fd) if cnt <= 0: try: os_remove(FILENAME) except OSError as oe: pass result = """<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n <e2simplexmlresult>\n <e2state>False</e2state> <e2statetext>Error writing to disk, not uploaded</e2statetext> </e2simplexmlresult>\n""" else: result = """<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n <e2simplexmlresult>\n <e2state>True</e2state> <e2statetext>%s</e2statetext> </e2simplexmlresult>\n""" % self.FILENAME return result
def __init__(self, plugin_name): from os import open as os_open, O_CREAT, O_TRUNC, O_RDWR self.__fd = os_open( PLUGIN_PATH + plugin_name, O_CREAT | O_TRUNC | O_RDWR ) self.__plugin_name = plugin_name # All keys in this dict correspond to a specific # offset in the mmapped file and all writes to # them propagate to the file self.__data_map = None # mmapped file offset, up to which # the data crc32 is calculated self.__data_crc32_end = None # JSON formatted metadata string self.__metadata_str = None # object returned by mmap() self.__buffer = None # list containing the format strings # of the respective datasources self.__format_list = None
def __init__(self, plugin_name): from os import open as os_open, O_CREAT, O_TRUNC, O_RDWR self.__fd = os_open(PLUGIN_PATH + plugin_name, O_CREAT | O_TRUNC | O_RDWR) self.__plugin_name = plugin_name # All keys in this dict correspond to a specific # offset in the mmapped file and all writes to # them propagate to the file self.__data_map = None # mmapped file offset, up to which # the data crc32 is calculated self.__data_crc32_end = None # JSON formatted metadata string self.__metadata_str = None # object returned by mmap() self.__buffer = None # list containing the format strings # of the respective datasources self.__format_list = None
def setDelay(self, device, value): #REP_DELAY if self.getDeviceAttribute(device, 'enabled'): print "[iInputDevices] setDelay for device %s to %d ms" % (device,value) event = struct.pack('iihhi', 0, 0, 0x14, 0x00, int(value)) fd = os_open("/dev/input/" + device, O_RDWR) os_write(fd, event) os_close(fd)
def lock_path(path, timeout): """ A context manager that attempts to gain an advisory lock for the path given within the timeout given. Raises LockPathTimeout if time expires before gaining the lock. If the lock is obtained, True is yielded and the lock relinquished with the context ends. For example:: with lock_path(path, timeout): # do things inside path knowing others using the same # advisory locking mechanism will be blocked until you're # done. :param path: The path to gain an advisory lock on. :param timeout: The number of seconds to wait to gain the lock before raising LockPathTimeout. """ fd = os_open(path, O_RDONLY) try: try_until = time() + timeout while True: try: flock(fd, LOCK_EX | LOCK_NB) break except IOError, err: if err.errno != EAGAIN: raise sleep(0.01) if time() >= try_until: raise LockPathTimeout( 'Timeout %ds trying to lock %r.' % (timeout, path)) yield True
def setRepeat(self, device, value): #REP_PERIOD if self.getDeviceAttribute(device, 'enabled') == True: print "[iInputDevices] setRepeat for device %s to %d ms" % (device,value) event = struct.pack('iihhi', 0, 0, 0x14, 0x01, int(value)) fd = os_open("/dev/input/" + device, O_RDWR) os_write(fd, event) os_close(fd)
def gpiod_chip_open(path: str) -> Optional[gpiod_chip]: """ @brief Open a gpiochip by path. @param path: Path to the gpiochip device file. @return GPIO chip handle or None if an error occurred. """ info = gpiochip_info() try: fd = os_open(path, O_RDWR | O_CLOEXEC) except FileNotFoundError: return None # We were able to open the file but is it really a gpiochip character # device? if not _is_gpiochip_cdev(path): os_close(fd) return None status = ioctl(fd, GPIO_GET_CHIPINFO_IOCTL, info) if status < 0: os_close(fd) return None if info.label[0] == "\0": label = "unknown" else: label = info.label.decode() return gpiod_chip( num_lines=info.lines, fd=fd, name=info.name.decode(), label=label )
def getInputDevices(self): for evdev in sorted(listdir("/dev/input")): try: fd = os_open("/dev/input/%s" % evdev, O_RDONLY | O_CLOEXEC) except: continue buf = "\0" * 256 try: size = ioctl(fd, EVIOCGNAME(len(buf)), buf) except: os_close(fd) continue os_close(fd) if size <= 0: continue name = buf[:size - 1] if name: if name == "dreambox advanced remote control (native)" and config.misc.rcused.value not in ( 0, 2): continue if name == "dreambox remote control (native)" and config.misc.rcused.value in ( 0, 2): continue if name == "dreambox front panel": continue self.Devices[evdev] = { 'name': name, 'type': self.getInputDeviceType(name), 'enabled': False, 'configuredName': None }
def setRepeat(self, device, value): #REP_PERIOD if self.getDeviceAttribute(device, 'enabled'): print "[iInputDevices] setRepeat for device %s to %d ms" % (device,value) event = struct.pack('iihhi', 0, 0, 0x14, 0x01, int(value)) fd = os_open("/dev/input/" + device, O_RDWR) os_write(fd, event) os_close(fd)
def loadConfigFile(self): print("[AutomaticVolumeAdjustmentConfig] Loading config file...") self.config = Config() if not os_path.exists(self.CONFIG_FILE): try: fd = os_open(self.CONFIG_FILE, os_O_RDWR | os_O_CREAT) os_close(fd) except Exception as e: print("Error: ", e) try: self.config.loadFromFile(self.CONFIG_FILE) except Exception as e: print("Error: ", e) self.config.entriescount = ConfigInteger(0) self.config.Entries = ConfigSubList() self.config.enable = ConfigYesNo(default=False) self.config.modus = ConfigSelection(choices=[ ("0", _("Automatic volume adjust")), ("1", _("Remember service volume value")) ], default="0") self.config.adustvalue = ConfigSelectionNumber(-50, 50, 5, default=25) self.config.mpeg_max_volume = ConfigSelectionNumber(10, 100, 5, default=100) self.config.show_volumebar = ConfigYesNo(default=False) self.initConfig()
def getInputDevices(self): devices = listdir("/dev/input/") for evdev in devices: if not evdev.startswith("event"): continue try: buffer = "\0" * 512 self.fd = os_open("/dev/input/" + evdev, O_RDWR | O_NONBLOCK) self.name = ioctl(self.fd, EVIOCGNAME(256), buffer) self.name = self.name[:self.name.find("\0")] os_close(self.fd) except (IOError, OSError), err: print '[iInputDevices] getInputDevices <ERROR: ioctl(EVIOCGNAME): ' + str( err) + ' >' self.name = None if self.name: if self.name == 'dreambox front panel': continue if self.name == "dreambox advanced remote control (native)" and config.misc.rcused.value == 1: continue if self.name == "dreambox remote control (native)" and config.misc.rcused.value != 1: continue self.Devices[evdev] = { 'name': self.name, 'type': self.getInputDeviceType(self.name), 'enabled': False, 'configuredName': None }
def getInputDevices(self): devices = listdir('/dev/input/') for evdev in devices: try: buffer = '\x00' * 512 self.fd = os_open('/dev/input/' + evdev, O_RDWR | O_NONBLOCK) self.name = ioctl(self.fd, EVIOCGNAME(256), buffer) self.name = self.name[:self.name.find('\x00')] if str(self.name).find('Keyboard') != -1: self.name = 'keyboard' os_close(self.fd) except (IOError, OSError) as err: print '[iInputDevices] getInputDevices <ERROR: ioctl(EVIOCGNAME): ' + str( err) + ' >' self.name = None if self.name: self.Devices[evdev] = { 'name': self.name, 'type': self.getInputDeviceType(self.name), 'enabled': False, 'configuredName': None } if getBoxType().startswith('et'): self.setDefaults(evdev)
def setDelay(self, device, value): if self.getDeviceAttribute(device, 'enabled'): print '[iInputDevices] setDelay for device %s to %d ms' % (device, value) event = struct.pack('iihhi', 0, 0, 20, 0, int(value)) fd = os_open('/dev/input/' + device, O_RDWR) os_write(fd, event) os_close(fd)
def openDeviceNodeForReadWrite(self): try: return os_open(self._device_node, O_RDWR) except Exception as e: logger.error("Could not open device node %s!", self._device_node, exc_info=True) return None
def setDelay(self, device, value): if self.getDeviceAttribute(device, 'enabled'): print '[iInputDevices] setDelay for device %s to %d ms' % (device, value) event = struct.pack('LLHHi', 0, 0, 20, 0, int(value)) fd = os_open('/dev/input/' + device, O_RDWR) os_write(fd, event) os_close(fd)
def set_file_permissions(): try: chmod(HOME + '/www/python/src/citer.log', 0o660) except FileNotFoundError: close( os_open(HOME + '/www/python/src/citer.log', O_CREAT | O_EXCL | O_WRONLY, 0o660)) chmod(HOME + '/www/python/src/config.py', 0o660)
def setDefaults(self, device): print "[iInputDevices] setDefaults for device %s" % device self.setDeviceAttribute(device, 'configuredName', None) event_repeat = struct.pack('iihhi', 0, 0, 0x14, 0x01, 100) event_delay = struct.pack('iihhi', 0, 0, 0x14, 0x00, 700) fd = os_open("/dev/input/" + device, O_RDWR) os_write(fd, event_repeat) os_write(fd, event_delay) os_close(fd)
def setDefaults(self, device): print "[iInputDevices] setDefaults for device %s" % (device) self.setDeviceAttribute(device, 'configuredName', None) event_repeat = struct.pack('iihhi', 0, 0, 0x14, 0x01, 100) event_delay = struct.pack('iihhi', 0, 0, 0x14, 0x00, 700) fd = os_open("/dev/input/" + device, O_RDWR) os_write(fd, event_repeat) os_write(fd, event_delay) os_close(fd)
async def read_pipe(file, size): loop = get_event_loop() reader = StreamReader() protocol = StreamReaderProtocol(reader) transport, _ = await loop.connect_read_pipe( lambda: protocol, fdopen(os_open(file, O_RDONLY | O_NONBLOCK))) data = await reader.read(size) transport.close() return data
def loadConfigFile(self): print "[AutomaticVolumeAdjustmentConfig] Loading config file..." self.config = Config() if not os_path.exists(self.CONFIG_FILE): try: fd = os_open( self.CONFIG_FILE, os_O_RDWR|os_O_CREAT) os_close( fd ) except Exception, e: print "Error: ", e
def loadConfigFile(self): print "[AutomaticVolumeAdjustmentConfig] Loading config file..." self.config = Config() if not os_path.exists(self.CONFIG_FILE): try: fd = os_open(self.CONFIG_FILE, os_O_RDWR | os_O_CREAT) os_close(fd) except Exception, e: print "Error: ", e
def setDefaults(self, device): print '[iInputDevices] setDefaults for device %s' % device self.setDeviceAttribute(device, 'configuredName', None) event_repeat = struct.pack('LLHHi', 0, 0, 20, 1, 100) event_delay = struct.pack('LLHHi', 0, 0, 20, 0, 700) fd = os_open('/dev/input/' + device, O_RDWR) os_write(fd, event_repeat) os_write(fd, event_delay) os_close(fd)
def set_file_permissions(): try: chmod(HOME + '/www/python/src/citer.log', 0o660) except FileNotFoundError: close(os_open( HOME + '/www/python/src/citer.log', O_CREAT | O_EXCL | O_WRONLY, 0o660)) chmod(HOME + '/www/python/src/config.py', 0o660)
def create(path): flags = ( # Create the subscription file O_CREAT # Fail if it already exists | O_EXCL # Open it for writing only | O_WRONLY) return fdopen(os_open(path.path, flags), "w")
def __enter__(self) -> Tuple[TextIO, TextIO]: fd_fileno = sfd_fileno = -1 try: # Follow our permission bits exactly -- don't use process permission # bits. orig_umask = umask(0) try: fd_fileno = os_open(self.filename, O_WRONLY | O_CREAT | O_TRUNC, 0o644) sfd_fileno = os_open(self.shadow_filename, O_WRONLY | O_CREAT | O_TRUNC, 0o600) finally: umask(orig_umask) lockf(fd_fileno, LOCK_EX) lockf(sfd_fileno, LOCK_EX) self.fd = open(fd_fileno, "w") self.sfd = open(sfd_fileno, "w") return (self.fd, self.sfd) except OSError: if sfd_fileno != -1: try: os_close(sfd_fileno) except OSError: pass try: unlink(self.shadow_filename) except OSError: pass if fd_fileno != -1: try: os_close(fd_fileno) except OSError: pass try: unlink(self.filename) except OSError: pass raise
def choose(): self.dir_name = filedialog.askdirectory(initialdir="") dda = DEFAULT_DIR_ADDRESS dn = self.dir_name if dn: try: dd = os_open(dda, O_CREAT | O_RDWR) except PermissionError: showerror(title="错误", message="请确保C盘用户文件夹有读写权限哦") else: if path.exists(dda): os_close(dd) os_remove(dda) dd = os_open(dda, O_CREAT | O_RDWR) os_write(dd, str.encode(dn)) os_close(dd) self.lb.config(text="已选择存储地址:%s" % dn, fg="#00FA9A", font=("simsun", "9")) else: self.lb.config(text="未选择存储地址", justify=LEFT, fg="#FA8072", font=("simsun", "9"))
def setDefaults(self, device): print '[InputDevice] setDefaults for device %s' % device self.setDeviceAttribute(device, 'configuredName', None) event_repeat = struct.pack('iihhi', 0, 0, 20, 1, 100) event_delay = struct.pack('iihhi', 0, 0, 20, 0, 700) fd = os_open('/dev/input/' + device, O_RDWR) os_write(fd, event_repeat) os_write(fd, event_delay) os_close(fd) return
def do_execute(self, stdin_file, stdout_file, stderr_file, cgroup_file): pid = fork() if not pid: chdir('/in/package') if stdin_file: fd = os_open(stdin_file, O_RDONLY) dup2(fd, STDIN_FILENO) os_close(fd) if stdout_file: fd = os_open(stdout_file, O_WRONLY) dup2(fd, STDOUT_FILENO) os_close(fd) if stderr_file: fd = os_open(stderr_file, O_WRONLY) dup2(fd, STDERR_FILENO) os_close(fd) if cgroup_file: enter_cgroup(cgroup_file) execve(self.execute_file, self.execute_args, SPAWN_ENV) return wait_and_reap_zombies(pid)
def loadConfigFile(self): print "[AutomaticVolumeAdjustmentConfig] Loading config file..." self.config = Config() if not os_path.exists(self.CONFIG_FILE): fd = os_open( self.CONFIG_FILE, os_O_RDWR|os_O_CREAT) os_close( fd ) self.config.loadFromFile(self.CONFIG_FILE) self.config.entriescount = ConfigInteger(0) self.config.Entries = ConfigSubList() self.config.enable = ConfigYesNo(default = False) self.config.adustvalue = ConfigInteger(default=25, limits=(0,95)) self.initConfig()
def __init__(self, filename, interface="", port=DEFAULT_PORT, buffer_size=DEFAULT_BUFFER_SIZE): super(UBDNetServer, self).__init__() self.fd = os_open(filename, O_RDWR | O_SYNC) self.size = lseek(self.fd, 0, SEEK_END) self.server = socket(AF_INET, SOCK_STREAM) self.server.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1) self.server.bind((interface, port)) self.server.listen(1) self.buffer_size = buffer_size lseek(self.fd, 0, SEEK_SET) return
def loadConfigFile(self): print "[AutomaticVolumeAdjustmentConfig] Loading config file..." self.config = Config() if not os_path.exists(self.CONFIG_FILE): fd = os_open( self.CONFIG_FILE, os_O_RDWR|os_O_CREAT) os_close( fd ) self.config.loadFromFile(self.CONFIG_FILE) self.config.entriescount = ConfigInteger(0) self.config.Entries = ConfigSubList() self.config.enable = ConfigYesNo(default = False) self.config.modus = ConfigSelection(choices = [("0", _("Automatic volume adjust")), ("1", _("Remember service volume value"))], default = "0") self.config.adustvalue = ConfigSelectionNumber(-50, 50, 5, default = 25) self.config.mpeg_max_volume = ConfigSelectionNumber(10, 100, 5, default = 100) self.config.show_volumebar = ConfigYesNo(default = False) self.initConfig()
def getInputDevices(self): devices = listdir("/dev/input/") for evdev in devices: try: buffer = "\0"*512 self.fd = os_open("/dev/input/" + evdev, O_RDWR | O_NONBLOCK) self.name = ioctl(self.fd, EVIOCGNAME(256), buffer) self.name = self.name[:self.name.find("\0")] os_close(self.fd) except (IOError,OSError), err: print '[iInputDevices] getInputDevices <ERROR: ioctl(EVIOCGNAME): ' + str(err) + ' >' self.name = None if self.name: self.Devices[evdev] = {'name': self.name, 'type': self.getInputDeviceType(self.name),'enabled': False, 'configuredName': None }
def lock_dir(path): path = path_join(path, '_-lock') fd = os_open(path, O_WRONLY | O_CREAT, 0o0600) try: for x in moves.range(100): try: flock(fd, LOCK_EX | LOCK_NB) break except IOError as err: if err.errno != EAGAIN: raise sleep(0.1) else: raise Exception('Timeout 10s trying to get lock on %r' % path) yield True finally: os_close(fd)
def sign( uid ): try: info = app.config[ 'REGISTERED_UIDS' ][ uid ] except KeyError: return None, None # not registered dest_dir = join( app.config[ 'UPLOAD_DIR' ], uid ) safe_makedirs( dest_dir ) try: fd = os_open( join( dest_dir, 'SIGNATURE.tsv' ), O_CREAT | O_EXCL | O_WRONLY, 0600 ) except OSError as e: if e.errno == EEXIST: return info, None # already signed else: raise else: signature = _sign( uid ) write( fd, u'{0}\t{1}\t{2}\n'.format( uid, info, request.remote_addr ).encode( 'utf8' ) ) close( fd ) return info, signature
def become_daemon(): try: pid = fork() except OSError: print 'unable to fork' exit(1) if pid == 0: # Daemonize setsid() # We redirect only the 3 first descriptors file_desc = os_open(devnull, O_RDWR) stdin.close() dup2(file_desc, 0) stdout.flush() dup2(file_desc, 1) stderr.flush() dup2(file_desc, 2) else: exit()
def getInputDevices(self): devices = listdir("/dev/input/") for evdev in devices: try: buffer = "\0"*512 self.fd = os_open("/dev/input/" + evdev, O_RDWR | O_NONBLOCK) self.name = ioctl(self.fd, EVIOCGNAME(256), buffer) self.name = self.name[:self.name.find("\0")] if str(self.name).find("Keyboard") != -1: self.name = 'keyboard' os_close(self.fd) except (IOError,OSError), err: print '[iInputDevices] getInputDevices ' + evdev + ' <ERROR: ioctl(EVIOCGNAME): ' + str(err) + ' >' self.name = None if self.name: self.Devices[evdev] = {'name': self.name, 'type': self.getInputDeviceType(self.name),'enabled': False, 'configuredName': None } if boxtype.startswith('et'): self.setDefaults(evdev) # load default remote control "delay" and "repeat" values for ETxxxx ("QuickFix Scrollspeed Menues" proposed by Xtrend Support)
def getInputDevices(self): devices = listdir("/dev/input") for evdev in devices: try: buffer = "\0" * 512 self.fd = os_open("/dev/input/by-id" + evdev, O_RDWR | O_NONBLOCK) self.name = ioctl(self.fd, EVIOCGNAME(256), buffer) self.name = self.name[: self.name.find("\0")] os_close(self.fd) except (IOError, OSError), err: print "[iInputDevices] getInputDevices <ERROR: ioctl(EVIOCGNAME): " + str(err) + " >" self.name = None if self.name: self.Devices[evdev] = { "name": self.name, "type": self.getInputDeviceType(self.name), "enabled": False, "configuredName": None, }
def getInputDevices(self): devices = listdir('/dev/input/') for evdev in devices: try: buffer = '\x00' * 512 self.fd = os_open('/dev/input/' + evdev, O_RDWR | O_NONBLOCK) self.name = ioctl(self.fd, EVIOCGNAME(256), buffer) self.name = self.name[:self.name.find('\x00')] if str(self.name).find('Keyboard') != -1: self.name = 'keyboard' os_close(self.fd) except (IOError, OSError) as err: print '[iInputDevices] getInputDevices <ERROR: ioctl(EVIOCGNAME): ' + str(err) + ' >' self.name = None if self.name: self.Devices[evdev] = {'name': self.name, 'type': self.getInputDeviceType(self.name), 'enabled': False, 'configuredName': None} if boxtype.startswith('et'): self.setDefaults(evdev)
def getInputDevices(self): devices = listdir("/dev/input/") for evdev in devices: try: buffer = "\0"*512 fd = os_open("/dev/input/" + evdev, O_RDWR | O_CLOEXEC) self.name = ioctl(fd, EVIOCGNAME(256), buffer) self.name = self.name[:self.name.find("\0")] os_close(fd) except (IOError,OSError), err: print '[iInputDevices] getInputDevices <ERROR: ioctl(EVIOCGNAME): ' + str(err) + ' >' self.name = None if self.name: if self.name == 'dreambox front panel': continue if self.name == "dreambox advanced remote control (native)" and config.misc.rcused.value not in (0, 2): continue if self.name == "dreambox remote control (native)" and config.misc.rcused.value in (0, 2): continue self.Devices[evdev] = {'name': self.name, 'type': self.getInputDeviceType(self.name),'enabled': False, 'configuredName': None }
def render_POST(self, req): req.setResponseCode(http.OK) req.setHeader('Content-type', 'application/xhtml+xml;' ) req.setHeader('charset', 'UTF-8') data = req.args['file'][0] if not data: result = """<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n <e2simplexmlresult>\n <e2state>False</e2state> <e2statetext>Filesize was 0, not uploaded</e2statetext> </e2simplexmlresult>\n""" return result fd = os_open( self.FILENAME, os_O_WRONLY|os_O_CREAT ) if fd: cnt = os_write(fd, data) os_close(fd) if cnt <= 0: try: os_remove(FILENAME) except OSError, oe: pass result = """<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n
def _WroteLockFile( sFileName, sContents='', iMode=IMODEWROTE ): # from os import makedirs, O_EXCL, O_CREAT, O_WRONLY, close, write from os import open as os_open from os.path import dirname, exists from errno import EEXIST # from Utils.Version import PYTHON3 # sLockDir = dirname(sFileName) # try: if sLockDir != '' and not exists(sLockDir): makedirs(sLockDir, iMode=IMODEMAKE) fd = os_open( sFileName, O_EXCL|O_CREAT|O_WRONLY, iMode ) except OSError: error, msg, traceback = exc_info() if msg.errno != EEXIST: raise msg return False else: if PYTHON3: sContents = bytes( sContents, 'utf-8' ) write( fd, sContents ) close(fd) return True
def daemonize(): from os import ( EX_OK, devnull, O_RDWR, fork, open as os_open, close as os_close, ) if fork(): exit(EX_OK) for fd in range(0, 3): try: os_close(fd) except OSError: pass os_open(devnull, O_RDWR) os_open(devnull, O_RDWR) os_open(devnull, O_RDWR)
def get_write_lock(): lock = os_open(Config.db_lock, O_RDWR | O_CREAT) lockf(lock, LOCK_EX) return lock
def __init__(self, lockpath, non_blocking): self.lockpath = lockpath self.non_blocking = non_blocking self.fd = os_open(self.lockpath, self.flags) self.acquired = self.closed = False
except OSError, e: exit(1) chdir("/") setsid() umask(0) try: pid = fork() if pid > 0: exit(0) except OSError, e: exit(1) close(0) close(1) close(2) os_open("/dev/null", O_RDWR) dup2(0,1) dup2(0,2) pf = open(pid_file, "w") pf.write(str(getpid())) pf.close() del pf print getcwd() app.run() else: application = app.wsgifunc()