def __setupTerminal(self): self.__terminalBackup = tcgetattr(stdin.fileno()) attr = tcgetattr(stdin.fileno()) attr[3] = attr[3] & ~ICANON attr[3] = attr[3] & ~ECHO tcsetattr(stdin.fileno(), TCSADRAIN, attr)
def main(): """Gets info and stores it at first run, otherwise updates DNS record.""" homedir = expanduser("~") install_location = (homedir + '/.dynflare') config_location = (install_location + '/data') if exists(install_location): email, api_key, zone, subdomain, zone_id, subdomain_id = RetrieveVariables( config_location) ip = GetIp() exisiting_record = GetExisitingRecord(email, api_key, zone_id, subdomain) if exisiting_record == ip: if isatty(stdin.fileno()): # Checks to see if interactive terminal print 'nothign to do!' else: pass else: response = UpdateRecord(email, api_key, zone_id, subdomain_id, subdomain, zone, ip, True) if isatty(stdin.fileno()): # Checks to see if interactive terminal print response else: pass else: FirstRun(install_location, config_location)
def myinput(timeout=0): ESCSEQ = b'\x1b[' tty.setraw(stdin.fileno()) #stdout = os.fdopen(stdin.fileno(), 'wb', 0) special = False while True: rlist, wlist, xlist = select([stdin], [], [], 0) ch = os.read(stdin.fileno(), 1) ch = ch.decode() if ch == '\x1b': if special: yield ESC else: special = True elif ch == '[': if not special: yield ch else: if special: special = False if ch == 'A': yield UP elif ch == 'B': yield DOWN elif ch == 'C': yield RIGHT elif ch == 'D': yield LEFT else: yield ch
def run_client(): ctx = zmq.Context() sub = ctx.socket(zmq.SUB) sub.connect('tcp://localhost:4455') sub.setsockopt(zmq.SUBSCRIBE, "") push = ctx.socket(zmq.PUSH) push.connect('tcp://localhost:4456') plr = zmq.Poller() plr.register(stdin.fileno(), zmq.POLLIN) plr.register(sub, zmq.POLLIN) while True: try: fds = dict(plr.poll()) except KeyboardInterrupt: print "\nClosing gracefully..." return if stdin.fileno() in fds: line = stdin.readline()[:-1] # trim newline char push.send(line) if sub in fds: msg = sub.recv() print "Got message: %r" % (msg,)
def nonblocking_readline(): global readbuffer #tty.setcbreak(stdin) # get flags associated with stdin fl = fcntl(stdin.fileno(), F_GETFL) # set the non blocking flag fcntl(stdin.fileno(), F_SETFL, fl | O_NONBLOCK) # try to read. We'll get nothing if there's no character to read. c = stdin.read(1) while c: # add char to our receive buffer readbuffer += c if ord(c) == 127: # sort of handle deletion - really only works if echoing is turned off readbuffer = readbuffer[:len(readbuffer) - 2] elif c == '\n': # if there's a newline, release the text newbuffer = readbuffer readbuffer = "" return newbuffer c = stdin.read(1) return ""
def main(): # Parse arguments if len(argv) != 3: print(f"Usage\n\t{argv[0]} <address> <port>") exit(1) try: # Parse arguments into server address server_address = (argv[1], int(argv[2])) # Try to connect to the server conn = create_connection(server_address) except ValueError as e: print(f"Error while trying to parse arguments {e}") exit(1) except OSError as e: print(f"Failed to connect to server {e}") exit(1) fd_map = { conn.fileno(): conn, stdin.fileno(): stdin } # Select loop, it will loop indefinitely waiting for events while True: l, m, n = select(fd_map, [], []) for fd in l: if fd == stdin.fileno(): # If the descriptor is stdin, then we need to send a msg handle_stdin(conn) elif fd == conn.fileno(): # If the descriptor is the server, then we received a msg handle_server(conn)
def posix_socket_shell(chan): oldtty = tcgetattr(stdin) try: setraw(stdin.fileno()) setcbreak(stdin.fileno()) chan.settimeout(0.0) while True: r, w, e = select([chan, stdin], [], []) if chan in r: try: x = chan.recv(1024).decode() if len(x) == 0: # EOF break stdout.write(x) stdout.flush() except timeout: pass if stdin in r: x = stdin.read(1) if len(x) == 0: break chan.send(x) finally: tcsetattr(stdin, TCSADRAIN, oldtty)
def getchar(): fd = stdin.fileno() old_settings = termios.tcgetattr(fd) try: tty.setraw(stdin.fileno()) ch = stdin.read(1) finally: termios.tcsetattr(fd, termios.TCSADRAIN, old_settings) return ch
def input_single_char(): fileno = stdin.fileno() stored_settings = termios.tcgetattr(fileno) try: tty.setraw(stdin.fileno()) char = stdin.read(1) finally: termios.tcsetattr(fileno, termios.TCSADRAIN, stored_settings) return char
def _pipeline(commands, env, fd_in, fd_out, fd_err): """Run a series of commands connected by their stdout/stdin.""" pids = [] first = True for i, command in enumerate(commands): last = i == len(commands) - 1 # If there are more commands upcoming then we need to set up a pipe. if not last: fd_in_new, fd_out_new = pipe2(O_CLOEXEC) pids += [fork()] child = pids[-1] == 0 if child: if not first: # Establish communication channel with previous process. dup2(fd_in_old, stdin_.fileno()) close_(fd_in_old) close_(fd_out_old) else: dup2(fd_in, stdin_.fileno()) if not last: # Establish communication channel with next process. close_(fd_in_new) dup2(fd_out_new, stdout_.fileno()) close_(fd_out_new) else: dup2(fd_out, stdout_.fileno()) # Stderr is redirected for all commands in the pipeline because each # process' output should be rerouted and stderr is not affected by # the pipe between the processes in any way. dup2(fd_err, stderr_.fileno()) _exec(*command, env=env) # This statement should never be reached: either exec fails in # which case a Python exception should be raised or the program is # started in which case this process' image is overwritten anyway. # Keep it to be absolutely safe. _exit(-1) else: if not first: close_(fd_in_old) close_(fd_out_old) else: first = False # If there are further commands then update the "old" pipe file # descriptors for future reference. if not last: fd_in_old = fd_in_new fd_out_old = fd_out_new return pids
def getChar(): fd = stdin.fileno() old_settings = tcgetattr(fd) try: setraw(stdin.fileno()) ch = stdin.read(1) finally: tcsetattr(fd, TCSADRAIN, old_settings) return ch
def getch(): f = stdin.fileno() o = tcgetattr(f) try: setraw(stdin.fileno()) char = stdin.read(1) finally: tcsetattr(f, TCSADRAIN, o) return char
def init(): flags = fcntl.fcntl(stdin.fileno(), fcntl.F_GETFL) if flags == flags | os.O_NONBLOCK: return else: rv = fcntl.fcntl(stdin.fileno(), fcntl.F_SETFL, flags | os.O_NONBLOCK) if rv == 0: print "ok" else: print "broken"
def cbreak(): if hasattr(stdin, "fileno") and os.isatty(stdin.fileno()): old_attrs = termios.tcgetattr(stdin) tty.setcbreak(stdin) tty.setraw(stdin) try: yield finally: if hasattr(stdin, "fileno") and os.isatty(stdin.fileno()): termios.tcsetattr(stdin, termios.TCSADRAIN, old_attrs)
def getch(): """Recebe e retorna um caractere digitado pelo usuário, sem ser necessário apertar 'enter'.""" fd = stdin.fileno() old_settings = tcgetattr(fd) try: setraw(stdin.fileno()) ch = stdin.read(1) finally: tcsetattr(fd, TCSADRAIN, old_settings) return ch
def get(self): """Code for controlling the user's interactions with the prompt Raises: KeyboardInterrupt: this re-implements the ability to us ^C during prompting """ fd = stdin.fileno() default = termios.tcgetattr(fd) tty.setraw(stdin.fileno()) # set terminal to raw input mode to get bytes while True: # read in until a key is pressed char = ord(stdin.read(1)) if char != "": break # logic for keyboard interrupt if char == 0x03: # is the input the interrupt code? termios.tcsetattr(fd, termios.TCSADRAIN, default) raise KeyboardInterrupt # logic for when the user hits enter elif char == 0x0D or char == 0x0A: # enter is one of these depending on system marked = self.mask[self.cursor_location] # toggle the corresponding spot in the selection mask self.mask[self.cursor_location] = not self.mask[self.cursor_location] current = self.options[self.cursor_location] if marked: # if the item was previously selected self.selected = list( filter(lambda item: item != current, self.selected) ) # remove item from selecteed else: # if not self.selected.append(current) # add it to the list of selected options # logic for arrow keys # these keypresses are three bytes long # the first byte is an escape character elif char == 0x1B: # check for escape character if ord(stdin.read(1)) == 0x5B: # check for next byte, same for up and down last = ord(stdin.read(1)) if last == 0x42: # up arrow # adjust the cursor position, wrapping if reached the end self.cursor_location = (self.cursor_location + 1) % len( self.options ) elif last == 0x41: # down arrow self.cursor_location = (self.cursor_location - 1) % len( self.options ) termios.tcsetattr( fd, termios.TCSADRAIN, default ) # reset the terminal out of raw mode
def getch(): ''' Get a single character from stdin and return it. Function blocks until character recieved. ''' fd = stdin.fileno() old_settings = tcgetattr(fd) setraw(stdin.fileno()) ch = stdin.read(1) tcsetattr(fd, TCSADRAIN, old_settings) return ch
def daemonize(self): """ Forks the process(es) from the controlling terminal and redirects I/O streams for logging. """ self.fork() chdir(getcwd()) setsid() umask(0) self.fork() stdout.flush() stderr.flush() si= file(self.stdin, 'w+') so= file(self.stdout, 'a+') se= file(self.stderr, 'a+', 0) dup2(si.fileno(), stdin.fileno()) dup2(so.fileno(), stdout.fileno()) dup2(se.fileno(), stderr.fileno()) register(self.del_pid) self.set_pid()
def pos(stream=stdout): '''Get cursor position.''' # Save term settings fd = stdin.fileno() prev = termios.tcgetattr(fd) stream.write("\033[6n") resp = "" ch = '' # Immitate getch() until 'R' (end of tty response, e.g. \033[1;1R) try: tty.setraw(fd) while ch!='R': ch = stdin.read(1) resp += ch finally: # Reset term mode termios.tcsetattr(fd, termios.TCSADRAIN, prev) try: # First two chars in response are \033 and [, last is R return [int(c) for c in resp[2:-1].split(';')] except: # In case of failure return [-1, -1]
def get_terminal_size_posix(): 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(stdin.fileno()) or \ ioctl_GWINSZ(stdout.fileno()) or \ ioctl_GWINSZ(stderr.fileno()) if not cr: try: with os.open(os.ctermid(), os.O_RDONLY) as fd: cr = ioctl_GWINSZ(fd) except: pass if not cr: try: cr = (os.environ['LINES'], os.environ['COLUMNS']) except: pass if not cr: raise TerminalError('cannot determine terminal size from POSIX') return int(cr[1]), int(cr[0])
def __init__(self, device, baudrate=115200, logfile=None, debug=False, twefirm=None, no_color=False, no_term=False): self._termstates = [] if platform != 'win32' and stdout.isatty(): self._termstates = [(fd, termios.tcgetattr(fd)) for fd in (stdin.fileno(), stdout.fileno(), stderr.fileno())] self._device = device self._baudrate = baudrate self._logfile = logfile self._port = self._open_port(self._device, self._baudrate, self._logfile, debug) self._resume = False self._debug = debug self._twefirm = twefirm self._twecmd = False self._tweformat = TWEDict.format_none self._twefmt_console = FmtAscii() self._twefmt_serail = None self._no_term = no_term TWELogger.__init__(self, no_color=no_color) if twefirm is not '': self._port.udev.set_baudrate(38400) self.tweprogram(twefirm)
def agility(job_file, add_option, njobs, time, mem, log, **options): is_pipe = not isatty(stdin.fileno()) if is_pipe: # get pipped in response pipestr = "" for line in sys.stdin: pipestr += line if not is_pipe and not job_file: logger.error("No Valid input. Job File: {}".format(job_file)) exit(1) if not os.path.exists(log): raise Exception('Log directory {} is not a directory or does not exist'.format(options['log'])) if is_pipe: try: jobs = yaml.load(pipestr, yaml.SafeLoader) except Exception as e: logger.error("Not Valid Json\n{}".format(pipestr)) exit(1) else: try: jobs = yaml.load(open(job_file), yaml.SafeLoader) except Exception as e: logger.error("Cannot open {} for reading.".format(job_file)) exit(1) batch_jobs(jobs, log=log, mem=mem, time=time, njobs=njobs)
def main(): global parser global verbose global pretty parser.add_argument("-v", "--verbose", dest="verbose", action='store_true', help="verbose output") parser.add_argument("-p", "--pretty", dest="pretty", action='store_true', help="pretty output. requires PTable module") parser.add_argument("-S", "--section", dest="section", default=None, help="""\ define a section in the following format; NAME SIZE SYM1 SYM2 SYM3 use SIZE as zero to skip size usage calculation \ """, action='append') options = parser.parse_args() is_pipe = not isatty(stdin.fileno()) if not is_pipe or not options.section: usage() quit(1) if options.verbose: verbose = True if options.pretty: pretty = True sections = parse_arg_sections(options.section) sizes = parse(sections) output(sizes)
def __init__(self): """Constructor""" self.__fd = stdin.fileno() self.__new = tcgetattr(self.__fd) self.__old = tcgetattr(self.__fd) self.__new[3] = (self.__new[3] & ~ICANON & ~ECHO) tcsetattr(self.__fd, TCSAFLUSH, self.__new)
def stdin_handler(): fcntl.fcntl(stdin, fcntl.F_SETFL, os.O_NONBLOCK) while True: wait_read(stdin.fileno()) cmd = stdin.readline().strip().lower() if cmd == 'quit': exit(0)
def run(self): """运行守护进程""" pid = os.fork() if pid > 0: exit(0) os.setsid() # 子进程创建新会话 os.chdir("/home/dnt") # 改变当前工作目录 os.umask(0) # 获取777权限 # 5. 关闭文件描述符 os.close(stdin.fileno()) os.close(stdout.fileno()) os.close(stderr.fileno()) # 【必须】6. 自己的逻辑代码 # 捕捉设置的定时器 signal.signal(signal.SIGALRM, self.heartbeat) # 第一次2s后执行,以后5s执行一次 signal.setitimer(signal.ITIMER_REAL, 2, 5) self.write_log("[%s]daeman running" % time.strftime("%Y-%m-%d %X")) self.write_log("p_name:%s,p_script:%s" % (self.p_name, self.p_script)) while True: time.sleep(5) # 不用担心影响signal(优先级别高)
def _daemonize(self): try: pid = os.fork() if pid > 0: exit() except OSError as e: error(_('Error entering daemon mode: %s') % e.strerror) exit() os.chdir('/') os.setsid() os.umask(0) stdout.flush() stderr.flush() si = open(os.devnull, 'r') so = open(os.devnull, 'a+') se = open(os.devnull, 'a+') os.dup2(si.fileno(), stdin.fileno()) os.dup2(so.fileno(), stdout.fileno()) os.dup2(se.fileno(), stderr.fileno()) on_exit(self._quit) old_log = getLogger() if old_log.handlers: for handler in old_log.handlers: old_log.removeHandler(handler) log(filename=self.logfile, level=self.loglevel, format='%(asctime)s %(levelname)-8s %(message)s') self._set_pid()
def connect(host, handshake): s = socket() s.connect((host, PORT)) s.send(handshake) print('Connected, press ^C or ^D to terminate the connection.') try: fd = stdin.fileno() old_settings = tcgetattr(fd) setraw(fd) while True: r, _, _ = select([stdin, s], [], []) for ready in r: if ready is s: r = s.recv(4096) if not r: print('Connection closed by remote peer', file=stderr) return stdout.write(r) stdout.flush() elif ready is stdin: r = stdin.read(1) if not r or chr(3) in r or chr(4) in r: s.shutdown(SHUT_RDWR) return s.send(r) finally: tcsetattr(fd, TCSADRAIN, old_settings)
def init_term(fullterm: bool) -> None: """Internal terminal initialization function""" if os_name == 'nt': return True if os_name == 'posix': import termios tfd = stdin.fileno() old = termios.tcgetattr(tfd) new = termios.tcgetattr(tfd) new[3] = new[3] & ~termios.ICANON & ~termios.ECHO new[6][termios.VMIN] = 1 new[6][termios.VTIME] = 0 if fullterm: new[6][termios.VINTR] = 0 new[6][termios.VSUSP] = 0 termios.tcsetattr(tfd, termios.TCSANOW, new) def cleanup_console(): termios.tcsetattr(tfd, termios.TCSAFLUSH, old) # terminal modes have to be restored on exit... register(cleanup_console) return True else: return True
def __enter__(self): self.fd = stdin.fileno() self.attr = tcgetattr(self.fd) newattr = tcgetattr(self.fd) newattr[3] = newattr[3] & ~ECHO tcsetattr(self.fd, TCSADRAIN, newattr) setraw(self.fd) return self
def inetd_sockets(max_socks): """ """ sock = fromfd(stdin.fileno()) stdin.close() stdout.close() stderr.close() return sock
def enableEchoMode(): fd = stdin.fileno() state = tcgetattr(fd) if state[TERMIO_LFLAGS] & ECHO: return False state[TERMIO_LFLAGS] = state[TERMIO_LFLAGS] | ECHO tcsetattr(fd, TCSADRAIN, state) return True
def clear(): # LIMPANDO A TELA import curses import termios from sys import stdin fd = stdin.fileno() scr = termios.tcgetattr(fd) scrn = curses.initscr() scrn.clear() termios.tcsetattr(fd, termios.TCSADRAIN, scr)
def getch(): file_descriptor = stdin.fileno() old_settings = tcgetattr(file_descriptor) try: setraw(file_descriptor) character = stdin.read(1) finally: tcsetattr(file_descriptor, TCSADRAIN, old_settings) return character
def get_term_colors(): if not stdin.isatty(): raise RuntimeError('<stdin> is not connected to a terminal') tc_save = None try: tc_save = termios.tcgetattr(stdin.fileno()) tc = termios.tcgetattr(stdin.fileno()) tc[3] &= ~termios.ECHO tc[3] &= ~termios.ICANON tc[6][termios.VMIN] = 0 tc[6][termios.VTIME] = 0 termios.tcsetattr(stdin.fileno(), termios.TCSANOW, tc) yield finally: if tc_save: termios.tcsetattr(stdin.fileno(), termios.TCSANOW, tc_save)
def getkey(): fd = sys.stdin.fileno() original_attributes = termios.tcgetattr(fd) try: tty.setraw(sys, stdin.fileno()) ch = sys.stdin.read(1) finally: termios.tcsetattr( fd, termios.TCSADRAIN, original_attributes) return ch
def main(): global incoming_port if len(sys.argv) != 3: print(f"Usage:\n\t{sys.argv[0]} <host> <port>") exit(1) # Bind to random socket and listen to incoming messages sock = socket(AF_INET, SOCK_STREAM) sock.bind(("", 0)) sock.listen(8) sock.setblocking(False) incoming_port = sock.getsockname()[1] # Connect to server server = Server(sys.argv[1], sys.argv[2]) # Advertise port server.send_port() # Get peers out_peers = server.get_peers() # A hashmap from socketid to socket select_map = {} select_map[sock.fileno()] = sock select_map |= map(lambda k: (k[0], k[1].out_sock), out_peers.items()) # Register stdin select_map[stdin.fileno()] = stdin while True: selected, x, y = select(select_map, [], []) for s in selected: # This means that a new client connected if s == sock.fileno(): conn, (host, port) = sock.accept() print(f"[i] + {host}:{port} Connected") handle_conn(conn, select_map) # This means that the user input a message elif s == stdin.fileno(): handle_stdin(stdin, select_map, sock.fileno()) # This means that a peer message was received else: f = select_map[s] handle_msg(f, select_map)
def daemonize(self): try: pid = fork() if pid > 0: # exit first parent _exit(0) except OSError as e: stderr.write( "fork #1 failed: {0:d} ({1:s})\n".format( e.errno, str(e) ) ) raise SystemExit(1) # decouple from parent environment chdir(self.path) setsid() umask(0) # do second fork try: pid = fork() if pid > 0: # exit from second parent _exit(0) except OSError as e: stderr.write( "fork #2 failed: {0:d} ({1:s})\n".format( e.errno, str(e) ) ) raise SystemExit(1) # redirect standard file descriptors stdout.flush() stderr.flush() maxfd = getrlimit(RLIMIT_NOFILE)[1] if maxfd == RLIM_INFINITY: maxfd = 2048 closerange(0, maxfd) si = open(self.stdin, "r") so = open(self.stdout, "a+") se = open(self.stderr, "a+") dup2(si.fileno(), stdin.fileno()) dup2(so.fileno(), stdout.fileno()) dup2(se.fileno(), stderr.fileno()) self.fire(writepid()) self.fire(daemonized(self))
def getch_non_blocking_2(): fd = stdin.fileno() old = termios.tcgetattr(fd) try: tty.setraw(fd) if select([stdin], [], [], 0)[0]: char = stdin.read(1) return char else: return None finally: termios.tcsetattr(fd, termios.TCSADRAIN, old)
def enableEchoMode(): """ Enable echo mode in the terminal. Return True if the echo mode is set correctly, or False if the mode was already set. """ fd = stdin.fileno() state = tcgetattr(fd) if state[TERMIO_LFLAGS] & ECHO: return False state[TERMIO_LFLAGS] = state[TERMIO_LFLAGS] | ECHO tcsetattr(fd, TCSADRAIN, state) return True
def read_colormap(): print "Reading color map from terminal, please wait... ", import tty, termios fd = stdin.fileno() old_settings = termios.tcgetattr(fd) try: tty.setraw(fd) for n, c in queryall(): CLUT[n] = c print '\r\033[K', finally: termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
def __call__(self, refresh): import tty, termios while True: fd = stdin.fileno() old_settings = termios.tcgetattr(fd) try: tty.setraw(stdin.fileno()) rlist, _, _ = select([stdin], [], [], refresh) if not rlist: return 'rr' ch = stdin.read(1) if not ch.isalnum(): if ch == '\x1b': return 'qq' # if we have an arrow if ch == "\x1B": stdin.read(2) return ch finally: termios.tcsetattr(fd, termios.TCSADRAIN, old_settings) return ch
def getch(): """ A getch for Linux Systems. """ file_descriptor = stdin.fileno() old_settings = tcgetattr(file_descriptor) try: setraw(file_descriptor) character = stdin.read(1) finally: tcsetattr(file_descriptor, TCSADRAIN, old_settings) return character
def daemonize(self): if fork(): exit(0) umask(0) setsid() if fork(): exit(0) stdout.flush() stderr.flush() si = file('/dev/null', 'r') so = file('/dev/null', 'a+') se = file('/dev/null', 'a+', 0) dup2(si.fileno(), stdin.fileno()) dup2(so.fileno(), stdout.fileno()) dup2(se.fileno(), stderr.fileno())
def _prompting_input(self): ''' Return prompting stdin.__iter__ decorator... If either: - prompt explicitly specified. - both stdin/out are a tty ''' if self.args.prompt or \ isatty(stdin.fileno()) and isatty(stdout.fileno()): return InteractiveInput(prompt=self.args.prompt or self.DEFAULT_PROMPT) else: return stdin
def getch(): stdout.flush() fd=stdin.fileno() if isatty(fd): oldset=tcgetattr(fd) newset=oldset[:] try: newset[3]&=-11 tcsetattr(fd, TCSANOW, newset) return ord(stdin.read(1)) finally:tcsetattr(fd, TCSANOW, oldset) else: fd=stdin.read(1) return ord(fd) if fd else -1
def nonblocking_readline(): global readbuffer #tty.setcbreak(stdin) # get flags associated with stdin fl = fcntl(stdin.fileno(), F_GETFL) # set the non blocking flag fcntl(stdin.fileno(), F_SETFL, fl | O_NONBLOCK) # try to read. We'll get nothing if there's no character to read. c = stdin.read(1) if c: # add char to our receive buffer readbuffer += c if ord(c) == 127: # sort of handle deletion - really only works if echoing is turned off readbuffer = readbuffer[:len(readbuffer)-2] elif c == '\n': # if there's a newline, release the text newbuffer = readbuffer readbuffer = "" return newbuffer return ""
def metadata_generator(): for input_ in inputs: if input_ == '-': log('Reading standard input') yield libxml2.readFd(stdin.fileno(), 'stdin', 'utf-8', 0) elif os.path.isfile(input_) or os.path.islink(input_): log('Reading file %s' % input_) yield libxml2.parseFile(input_) elif os.path.isdir(input_): log('Reading directory %s' % input_) for metadata in iter_directory(input_, options.recurse): yield metadata else: # it must be a URL log('Reading URL %s' % input_) yield libxml2.parseFile(input_)
def __init__(self, device, baudrate=None, parity=None, rtscts=False, debug=False): self._termstates = [] if not mswin and stdout.isatty(): self._termstates = [(fd, tcgetattr(fd)) for fd in (stdin.fileno(), stdout.fileno(), stderr.fileno())] self._device = device self._baudrate = baudrate or self.DEFAULT_BAUDRATE self._port = self._open_port(self._device, self._baudrate, parity, rtscts, debug) self._resume = False self._silent = False self._rxq = deque() self._rxe = Event() self._debug = debug register(self._cleanup)
def getchs(): """ Block until there are bytes to read on stdin and then return them all. Adapted from getch() https://github.com/joeyespo/py-getch. """ fd = stdin.fileno() old = termios.tcgetattr(fd) setNonBlocking(fd) try: tty.setraw(fd) while not select([stdin], [], [], 0)[0]: sleep(POLL_INTERVAL) return stdin.read() finally: termios.tcsetattr(fd, termios.TCSADRAIN, old)
def daemonize(): from os import fork, chdir, setsid, umask, getpid, dup2 from sys import stdout, stderr, stdin, exit if fork(): exit(0) chdir("/") setsid() umask(0) if fork(): exit(0) stdout.flush() stderr.flush() n1 = open('/dev/null', 'r') n2 = open('/dev/null', 'w') dup2(n1.fileno(), stdin.fileno()) dup2(n2.fileno(), stdout.fileno()) dup2(n2.fileno(), stderr.fileno()) return getpid()
def Launch(cmd, no_stdout, env): global fds global c c = c + 1 #cmd = ["/usr/bin/timeout", "-k", "1", "3"]+cmd #print cmd if cmd[-1][0:2] == "< ": filename = cmd[-1].replace("< ", "") #try: # close(3) #except OSError: # print "OsError!" # pass for fd in fds: #print fd, try: close(fd) #print "closed!" except OSError: #print "failed close!" pass fds = [] desc = fopen(filename,O_RDONLY) fds.append(desc) dup2(desc, stdin.fileno()) fds.append(desc) #close(desc) cmd = cmd[:-1] #print "c:", c #print "self pid", getpid() r = createChild(cmd, no_stdout, env) #print "new pid", r #print "self pid", getpid() #print "Done!" return r
def finput(st,ec,ep): global input_buf from os import O_NONBLOCK from fcntl import fcntl, F_SETFL fcntl(stdin.fileno(), F_SETFL, O_NONBLOCK) try: l = stdin.readline() l = input_buf + l if len(l) == 0: ec[:]=[atom2i('exit')] while '\n' in l: (c,l) = l.split('\n',1) ep.append(ec.copy()) ec[:] = re(c) input_buf = l except IOError as e: if e.errno != 11: raise