def __init__(self, speed=4800, databits=8, parity='N', stopbits=1): # Allow Serial: header to be overridden by explicit spped. self.speed = speed baudrates = { 0: termios.B0, 50: termios.B50, 75: termios.B75, 110: termios.B110, 134: termios.B134, 150: termios.B150, 200: termios.B200, 300: termios.B300, 600: termios.B600, 1200: termios.B1200, 1800: termios.B1800, 2400: termios.B2400, 4800: termios.B4800, 9600: termios.B9600, 19200: termios.B19200, 38400: termios.B38400, 57600: termios.B57600, 115200: termios.B115200, 230400: termios.B230400, } speed = baudrates[speed] # Throw an error if the speed isn't legal (self.fd, self.slave_fd) = os.openpty() self.byname = os.ttyname(self.slave_fd) print os.ttyname(self.slave_fd), os.ttyname(self.fd) opencpn_conf = ConfigParser.RawConfigParser() opencpn_conf.read(os.getenv('HOME') + "/.opencpn/opencpn.conf") opencpn_conf.set("Settings/NMEADataSource", "Source", "Serial:AIS Port (Shared)") opencpn_conf.set("Settings/AISPort", "Port", "Serial:" + os.ttyname(self.slave_fd)) opencpn_conf_file = open(os.getenv('HOME') + "/.opencpn/opencpn.conf", "w") opencpn_conf.write(opencpn_conf_file) opencpn_conf_file.close() (iflag, oflag, cflag, lflag, ispeed, ospeed, cc) = termios.tcgetattr(self.slave_fd) cc[termios.VMIN] = 1 cflag &= ~(termios.PARENB | termios.PARODD | termios.CRTSCTS) cflag |= termios.CREAD | termios.CLOCAL iflag = oflag = lflag = 0 iflag &=~ (termios.PARMRK | termios.INPCK) cflag &=~ (termios.CSIZE | termios.CSTOPB | termios.PARENB | termios.PARODD) if databits == 7: cflag |= termios.CS7 else: cflag |= termios.CS8 if stopbits == 2: cflag |= termios.CSTOPB if parity == 'E': iflag |= termios.INPCK cflag |= termios.PARENB elif parity == 'O': iflag |= termios.INPCK cflag |= termios.PARENB | termios.PARODD ispeed = ospeed = speed termios.tcsetattr(self.slave_fd, termios.TCSANOW, [iflag, oflag, cflag, lflag, ispeed, ospeed, cc])
def step_impl(ctx): pid, fd = pty.fork() if pid == pty.CHILD: tty = os.ttyname(0) sys.stdin = open(tty, 'r') sys.stdout = open(tty, 'w') sys.stderr = open(tty, 'w') try: dockerpty.start(ctx.client, ctx.container) except Exception as e: raise e os._exit(1) else: os._exit(0) else: tty = os.ttyname(fd) ctx.pty = fd util.set_pty_size( ctx.pty, (ctx.rows, ctx.cols) ) ctx.pid = pid util.wait(ctx.pty, timeout=5) time.sleep(1) # give the terminal some time to print prompt
def mkpty(): master1, slave = pty.openpty() slaveName1 = os.ttyname(slave) master2, slave = pty.openpty() slaveName2 = os.ttyname(slave) print '\nslave device names: ', slaveName1, slaveName2 return master1, master2
def fetch_api_lock(): """Context manager to setup and gain a lock on the serial port""" app = app_test.test_client() app.testing = True master_pty, slave_pty = pty.openpty() slave_port = os.ttyname(slave_pty) master_port = os.ttyname(master_pty) lock_response = app.get('/open') # assert lock_response.status_code == 201 print(lock_response) print(lock_response.get_data()) json_data = json.loads(lock_response.get_data().decode('ascii')) lock = str(json_data.get('api_lock', '')) yield ( app, master_pty, slave_pty, master_port, slave_port, lock_response, lock) os.close(master_pty) os.close(slave_pty) app.get('/close')
def __redirect_file_descriptors(): import resource # POSIX resource information maxfd = resource.getrlimit(resource.RLIMIT_NOFILE)[1] if maxfd == resource.RLIM_INFINITY: maxfd = MAXFD # Close all file descriptors. for fd in range(0, maxfd): # Only close TTYs. try: _os.ttyname(fd) except: continue try: _os.close(fd) except OSError: # File descriptor wasn't open. Ignore. pass # Redirect standard input, output and error to something safe. # os.open() is guaranteed to return the lowest available file # descriptor (0, or standard input). Then, we can dup that # descriptor for standard output and standard error. _os.open(NULL_DEVICE, _os.O_RDWR) _os.dup2(0, 1) _os.dup2(0, 2)
def step_impl(ctx): pid, fd = pty.fork() if pid == pty.CHILD: tty = os.ttyname(0) sys.stdin = open(tty, 'r') sys.stdout = open(tty, 'w') sys.stderr = open(tty, 'w') try: dockerpty.start(ctx.client, ctx.container) except Exception as e: raise e os._exit(1) else: os._exit(0) else: try: tty = os.ttyname(fd) except OSError as ex: # Not supported on OS X. But since we're not using this # TTY name anyway, let the test pass. tty = 'OSX' ctx.pty = fd util.set_pty_size( ctx.pty, (ctx.rows, ctx.cols) ) ctx.pid = pid util.wait(ctx.pty, timeout=5) time.sleep(1) # give the terminal some time to print prompt
def is_interactive(self, fh): fd = fh.obj.fileno() try: os.ttyname(fd) return True except OSError: return False
def main(): """Program entry point.""" fd = sys.stdin.fileno() locale.setlocale(locale.LC_ALL, '') encoding = locale.getpreferredencoding() print('os.isatty({0}) => {1}'.format(fd, os.isatty(fd))) print('locale.getpreferredencoding() => {0}'.format(encoding)) display_pathconf(names=os.pathconf_names, getter=lambda name: os.fpathconf(fd, name)) try: (iflag, oflag, cflag, lflag, _, _, # input / output speed (bps macros) ctlc) = termios.tcgetattr(fd) except termios.error as err: print('stdin is not a typewriter: {0}'.format(err)) else: display_bitmask(kind=' Input Mode', bitmap=BITMAP_IFLAG, value=iflag) display_bitmask(kind=' Output Mode', bitmap=BITMAP_OFLAG, value=oflag) display_bitmask(kind='Control Mode', bitmap=BITMAP_CFLAG, value=cflag) display_bitmask(kind=' Local Mode', bitmap=BITMAP_LFLAG, value=lflag) display_ctl_chars(index=CTLCHAR_INDEX, ctlc=ctlc) print('os.ttyname({0}) => {1}'.format(fd, os.ttyname(fd))) print('os.ctermid() => {0}'.format(os.ttyname(fd)))
def fork(handle_window_size=False): # copied from pty.py, with modifications master_fd, slave_fd = openpty() slave_name = os.ttyname(slave_fd) pid = os.fork() if pid == CHILD: # Establish a new session. os.setsid() os.close(master_fd) if handle_window_size: clone_window_size_from(slave_name, STDIN_FILENO) # Slave becomes stdin/stdout/stderr of child. os.dup2(slave_fd, STDIN_FILENO) os.dup2(slave_fd, STDOUT_FILENO) os.dup2(slave_fd, STDERR_FILENO) if (slave_fd > STDERR_FILENO): os.close (slave_fd) # Explicitly open the tty to make it become a controlling tty. tmp_fd = os.open(os.ttyname(STDOUT_FILENO), os.O_RDWR) os.close(tmp_fd) else: os.close(slave_fd) # Parent and child process. return pid, master_fd, slave_name
def test_047_ttyname(): # issue #47 {{{1 import os try: os.ttyname(0) os.ttyname(1) except Exception as e: print(e) return False return True
def __init__(self, outfp, charset): ColorTerminalInterface.__init__(self, outfp, charset) from termios import TIOCGWINSZ from fcntl import ioctl from struct import unpack fileno = outfp.fileno() os.ttyname(fileno) (self.lines, self.cols, _x, _y) = unpack('HHHH', ioctl(fileno, TIOCGWINSZ, '_'*8)) self.x11display = os.environ.get("DISPLAY") return
def infofunc(): ''' Print system information to stdout ''' S = lambda cmd : spawn_pipe(*(cmd.split())) uname = os.uname() printtag('User', env('USER')) printtag('Home', home) printtag('Hostname', uname.nodename) printtag('Distribution', distro) osname = (S('uname --operating-system'), uname.sysname, uname.release) printtag('Operating system', '%s with %s %s kernel' % osname) printtag('Kernel version', uname.version) printtag('Processor architecture', uname.machine) if os.path.exists('/proc'): try: cpuinfo = cat('/proc/cpuinfo').split('\n') cpu = [line for line in cpuinfo if line.startswith('model name')] for cpu in [line.split(':')[1] for line in unique(sorted(cpu))]: printtag('Processor model', cpu.strip()) cpu = sum([float(line.split(':')[1].strip()) for line in cpuinfo if line.startswith('cpu MHz')]) printtag('Current CPU speed', '%.0f MHz' % cpu) except: pass try_(lambda : printtag('Load average', cat('/proc/loadavg'))) try_(lambda : printtag('Uptime', '%s %s' % tuple([strdur(c) for c in cat('/proc/uptime').split()]))) try: mem = cat('/proc/meminfo').split('\n') mem = dict([[cell.strip() for cell in line.split(':')[:2]] for line in mem]) try_(lambda : printtag('Total memory', '%s + %s swap' % (mem['MemTotal'], mem['SwapTotal']))) try_(lambda : printtag('Hardware corrupted memory', mem['HardwareCorrupted'])) try_(lambda : printtag('Kernel memory', '%s stack + %s slab' % (mem['KernelStack'], mem['Slab']))) try_(lambda : printtag('Shared memory', mem['Shmem'])) try_(lambda : printtag('Locked memory', '%s, %s unevictable' % (mem['Mlocked'], mem['Unevictable']))) try_(lambda : printtag('Memory buffers', mem['Buffers'])) try_(lambda : printtag('Cached memory', '%s + %s swap' % (mem['Cached'], mem['SwapCached']))) except: pass try: route = [line.split('\t')[2] for line in cat('/proc/net/route').split('\n')] route = [line for line in route if ('Gateway' not in line) and ('00000000' not in line)] for g in route: g = '%i.%i.%i.%i' % (int(g[6:8], 16), int(g[4:6], 16), int(g[2:4], 16), int(g[0:2], 16)) printtag('Default gateway', g) except: pass printtag('Shell', env('SHELL')) printtag('Shell version', spawn_pipe(env('SHELL'), '--version').split('\n')[0]) printtag('Teletypewriter', try_(lambda : os.ttyname(2), lambda : os.ttyname(0))) printtag('Terminal', '%s %s' % (env('TERM'), env('COLORTERM'))) printtag('X display', env('DISPLAY')) printtag('Wayland display', env('WAYLAND_DISPLAY')) printtag('Window manager', env('DESKTOP_SESSION')) printtag('Editor', env('EDITOR')) printtag('Locale', env('LANG'))
def is_interactive(self): fd = self.obj.fileno() if hasattr(os, "ttyname"): try: os.ttyname(fd) return True except OSError: return False else: # Not perfect, but best you can do on non-posix to detect a terminal. return sys.stdin.isatty() or sys.stdout.isatty()
def shell(self): try: os.chdir(self.path or self.callee.dir) except Exception: pass env = os.environ # If local and local user is the same as login user # We set the env of the user from the browser # Usefull when running as root if self.caller == self.callee: env.update(self.socket.env) env["TERM"] = "xterm-256color" env["COLORTERM"] = "butterfly" env["HOME"] = self.callee.dir # print(self.callee.dir) env["LOCATION"] = "http%s://%s:%d/" % ( "s" if not True else "", "localhost", 8001) env["PATH"] = '%s:%s' % (os.path.abspath(os.path.join( os.path.dirname(__file__), 'bin')), env.get("PATH")) try: tty = os.ttyname(0).replace('/dev/', '') except Exception: tty = '' if self.caller != self.callee: try: os.chown(os.ttyname(0), self.callee.uid, -1) except Exception: pass utils.add_user_info( self.uid, tty, os.getpid(), self.callee.name, self.request.headers['Host']) if os.path.exists('/usr/bin/su'): args = ['/usr/bin/su'] else: args = ['/bin/su'] if sys.platform == 'linux': args.append('-p') if tornado.options.options.shell: args.append('-s') args.append(tornado.options.options.shell) args.append(self.callee.name) os.execvpe(args[0], args, env)
def __call__(self, image, cmd, work_dir=None, remove=True): basic_docker_args = [ '--workdir=' + (work_dir or '/'), ] if self.entrypoint: basic_docker_args.append('--entrypoint=' + self.entrypoint) if ( self.forward_ssh_agent and 'SSH_AUTH_SOCK' in os.environ and os.path.exists(os.environ['SSH_AUTH_SOCK']) ): auth_sock = '/run/ssh_auth_sock' basic_docker_args.extend([ '--volume=' + os.environ['SSH_AUTH_SOCK'] + ':' + auth_sock + ':rw', '--env=SSH_AUTH_SOCK=' + auth_sock, ]) try: os.ttyname(sys.stdin.fileno()) except EnvironmentError: pass # stdin is not a tty else: basic_docker_args.extend([ '--tty', '--interactive', ]) def check_call_log(args, level=logging.INFO): logging.log(level, args) check_call(args, shell=False) args = ['docker', 'run'] + basic_docker_args + list(self.docker_args) if remove: check_call_log(args + ['--rm'] + [image] + cmd) return None else: with make_tmpdir() as tmpdir: cidfile = os.path.join(tmpdir, 'cid') check_call_log(( args + ['--cidfile=' + cidfile] + [image] + cmd )) with open(cidfile) as cidfobj: return cidfobj.read().strip()
def tty(args, stdin, stdout, stderr): """A tty command for xonsh.""" if "--help" in args: print(TTY_HELP, file=stdout) return 0 silent = False for i in ("-s", "--silent", "--quiet"): if i in args: silent = True args.remove(i) if len(args) > 0: if not silent: for i in args: print("tty: Invalid option: {}".format(i), file=stderr) print("Try 'tty --help' for more information", file=stderr) return 2 try: fd = stdin.fileno() except: fd = sys.stdin.fileno() if not os.isatty(fd): if not silent: print("not a tty", file=stdout) return 1 if not silent: try: print(os.ttyname(fd), file=stdout) except: return 3 return 0
def fork(): try: (pid, fd) = os.forkpty() except (AttributeError, OSError): pass if pid == CHILD: try: os.setsid() except OSError: pass return (pid, fd) (master_fd, slave_fd) = openpty() pid = os.fork() if pid == CHILD: os.setsid() os.close(master_fd) os.dup2(slave_fd, STDIN_FILENO) os.dup2(slave_fd, STDOUT_FILENO) os.dup2(slave_fd, STDERR_FILENO) if slave_fd > STDERR_FILENO: os.close(slave_fd) tmp_fd = os.open(os.ttyname(STDOUT_FILENO), os.O_RDWR) os.close(tmp_fd) else: os.close(slave_fd) return (pid, master_fd)
def _IdentifyTTY(): for source in (sys.stdin, sys.stdout, sys.stderr): try: return os.ttyname(source.fileno()) except EnvironmentError, e: if e.errno not in (errno.EINVAL, errno.ENOTTY): raise
def fork(): """fork() -> (pid, master_fd) Fork and make the child a session leader with a controlling terminal.""" try: pid, fd = os.forkpty() except (AttributeError, OSError): pass else: if pid == CHILD: try: os.setsid() except OSError: pass return (pid, fd) master_fd, slave_fd = openpty() pid = os.fork() if pid == CHILD: os.setsid() os.close(master_fd) os.dup2(slave_fd, STDIN_FILENO) os.dup2(slave_fd, STDOUT_FILENO) os.dup2(slave_fd, STDERR_FILENO) if slave_fd > STDERR_FILENO: os.close(slave_fd) tmp_fd = os.open(os.ttyname(STDOUT_FILENO), os.O_RDWR) os.close(tmp_fd) else: os.close(slave_fd) return (pid, master_fd)
def __init__(self, parent=None): """Initialise Linux pseudo terminal """ QThread.__init__(self, parent) self.master, self.slave = pty.openpty() self.ptyname = os.ttyname(self.slave) self.stop = False
def get_socket(cls): """Get a connected, ready-to-use socket for gpg-agent.""" agent_info = os.environ.get("GPG_AGENT_INFO") if agent_info is None: raise GPGAgentStoreConnectionError("no $GPG_AGENT_INFO env var") socket_address = agent_info.split(":")[0] gpg_socket = socket.socket(socket.AF_UNIX) try: gpg_socket.connect(socket_address) except socket.error as exc: raise GPGAgentStoreConnectionError("socket error: %s" % exc) cls._socket_receive(gpg_socket, b"^OK .*\n") gpg_socket.send(b"GETINFO socket_name\n") reply = cls._socket_receive(gpg_socket, b"^(?!OK)[^ ]+ .*\n") if not reply.startswith(b"D"): raise GPGAgentStoreConnectionError( "socket: bad reply: %r" % reply) reply_socket_address = reply.split()[1] if reply_socket_address != socket_address: # The gpg-agent documentation advises making this check. raise GPGAgentStoreConnectionError("daemon socket mismatch") tty = os.environ.get("GPG_TTY") if tty is None: if not sys.stdin.isatty(): raise GPGAgentStoreConnectionError( "no $GPG_TTY env var and failed to extrapolate it") tty = os.ttyname(sys.stdin.fileno()) gpg_socket.send(b"OPTION putenv=GPG_TTY=%s\n" % tty) cls._socket_receive(gpg_socket, b"^OK\n") for name in ("TERM", "LANG", "LC_ALL", "DISPLAY"): val = os.environ.get(name) if val is not None: gpg_socket.send(b"OPTION putenv=%s=%s\n" % (name, val)) cls._socket_receive(gpg_socket, b"^OK\n") return gpg_socket
def run_script(_pipe, _io, ctx): sys.stdout = os.fdopen(_pipe, "w") sys.stderr = os.fdopen(_pipe, "w") sys.stdin = os.fdopen(_pipe, "r") # Explicitly open the tty to make it become a controlling tty. tmp_fd = os.open(os.ttyname(_pipe), os.O_RDWR) os.close(tmp_fd) os.setsid() try: from features.steps import mp_setup mp_setup(ctx) except ImportError: pass try: from setproctitle import setproctitle setproctitle("python process: {}".format(fullname)) except ImportError: pass for name, value in ctx.environ.iteritems(): os.environ[name] = value os.chdir(ctx.cwd) sys.argv = ["-"] if ctx.args: sys.argv += shlex.split(ctx.args) else: sys.argv = ["me"] getattr(import_module(module), target)()
def getargv(self): """Return the gdb argv list.""" argv = [self.pgm] # Use pyclewn tty as the debuggee standard input and output, # but not when vim is run as 'vim' or 'vi'. # May be overriden by --args option on pyclewn command line. vim_pgm = os.path.basename(self.options.editor) if os.name != 'nt': if (not self.options.daemon and vim_pgm != 'vim' and vim_pgm != 'vi' and hasattr(os, 'isatty') and os.isatty(0)): terminal = os.ttyname(0) else: terminal = os.devnull argv += ['-tty=%s' % terminal] # build the gdb init temporary file try: self.f_init = misc.TmpFile('gdbscript') self.f_init.write(GDB_INIT) finally: if self.f_init: self.f_init.close() argv += ['-x'] + [self.f_init.name] + ['--interpreter=mi'] if self.arglist: argv += self.arglist return argv
def is_terminal(path=None): """Is true if the terminal is a real one Like the linux terminal console >>> is_terminal("/dev/tty0") True >>> is_terminal("/dev/ttyUSB0") False >>> is_terminal("/dev/ttyS0") False >>> is_terminal("/dev/tty") True >>> is_terminal("/dev/console") True """ is_terminal = False try: ttyname = path or os.ttyname(sys.stdin.fileno()) is_tty = re.match("/dev/tty([0-9]|$)", ttyname) is not None is_console = ttyname == "/dev/console" is_terminal = is_tty or is_console except OSError: pass return is_terminal
def _start_gdb_process(self): ''' Spawn a GDB process. The attributes gdb, gdbInput and gdbOutput will become valid. ''' cfg = globalconfig.get_global_config() use_gdb_system = cfg.getboolean('gdb', 'use-gdb-system') gdb_args = ["-interpreter=mi", "-quiet"] if use_gdb_system: gdb_path = 'gdb' else: gdb_path = cfg.get('gdb', 'gdb-executable-path') gdb_data_path = cfg.get('gdb', 'gdb-data-directory') data_directory_option = "--data-directory=%s" % gdb_data_path gdb_args.append(data_directory_option) # TODO stderr = /dev/null?? this is simple, but some errors of gdb may be missing self.gdb = subprocess.Popen([gdb_path] + gdb_args, stdin=PIPE, stdout=PIPE, stderr=open('/dev/null', 'w')) self.gdbInput = self.gdb.stdin self.gdbOutput = self.gdb.stdout self.gdb_pid = self.gdb.pid self.terminal_master, self.terminal_slave = pty.openpty() self.terminal_name = os.ttyname(self.terminal_slave)
def setUp(self): #Fixtures self.test_temp_str = '{"Ta":22.51, "To":[20.27,20.50,19.27,19.62,20.07,19.25,20.29,19.98,20.83,19.63,19.18,' \ '19.76,20.49,20.74,19.87,19.92,19.80,19.26,20.46,19.71,19.93,19.47,19.39,19.44,19.62,' \ '20.96,21.69,21.14,26.39,24.74,25.16,26.20,26.75,26.74,26.76,26.91,26.09,27.12,26.79,' \ '26.20,27.24,26.20,25.89,26.26,26.94,26.94,24.92,25.96,26.77,26.72,25.36,25.26,26.54,' \ '26.45,26.14,26.58,23.69,26.38,26.71,26.82,20.41,21.05,21.07,22.82]}\r\n' self.test_temp = [20.27, 20.50, 19.27, 19.62, 20.07, 19.25, 20.29, 19.98, 20.83, 19.63, 19.18, 19.76, 20.49, 20.74, 19.87, 19.92, 19.80, 19.26, 20.46, 19.71, 19.93, 19.47, 19.39, 19.44, 19.62, 20.96, 21.69, 21.14, 26.39, 24.74, 25.16, 26.20, 26.75, 26.74, 26.76, 26.91, 26.09, 27.12, 26.79, 26.20, 27.24, 26.20, 25.89, 26.26, 26.94, 26.94, 24.92, 25.96, 26.77, 26.72, 25.36, 25.26, 26.54, 26.45, 26.14, 26.58, 23.69, 26.38, 26.71, 26.82, 20.41, 21.05, 21.07, 22.82] self.test_ambient_temp = 22.51 self.test_temp_str2 = '{"Ta":30.73, "To":[30.81,23.60,23.04,21.81,22.49,22.51,22.02,22.48,21.56,21.65,' \ '21.65,21.51,22.08,22.18,22.14,21.58,22.54,22.21,22.23,22.54,21.77,21.88,21.86,' \ '22.58,21.03,21.55,21.21,21.78,21.08,21.57,21.57,21.44,21.46,22.63,21.94,22.61,' \ '21.48,21.93,21.93,22.22,21.46,21.92,21.91,21.02,21.44,21.90,21.15,21.39,20.55,' \ '21.88,21.86,22.18,21.75,20.71,21.07,20.87,21.70,20.96,20.17,21.31,21.62,19.94,' \ '20.43,20.69]}\r\n' self.test_ambient_temp2 = 30.73 #Use posix.openpty to create dummy Serial Port for Testing #http://stackoverflow.com/questions/2174071/how-to-use-dev-ptmx-for-create-a-virtual-serial-port self.fd_master, self.fd_slave = posix.openpty() self.test_sensor_config = MLX90620SensorProperties(arg_name='TestNode', arg_port=os.ttyname(self.fd_slave), arg_time_between_ambient_temp=0.2) #print self.test_sensor_config.__dict__ self.test_sensor = MLX90620(self.test_sensor_config)
def alloc_pty(ctx, f, *args, **kwargs): pid, fd = pty.fork() if pid == pty.CHILD: tty = os.ttyname(0) sys.stdin = open(tty, 'r') sys.stdout = open(tty, 'w') sys.stderr = open(tty, 'w') # alternative way of doing ^ is to do: # kwargs["stdout"] = open(tty, 'w') # kwargs["stderr"] = open(tty, 'w') # kwargs["stdin"] = open(tty, 'r') # Create a new client for the child process to avoid concurrency issues client = get_client() f(client, *args, **kwargs) sys.exit(0) else: ctx.pty = fd util.set_pty_size( ctx.pty, (ctx.rows, ctx.cols) ) ctx.pid = pid util.wait(ctx.pty, timeout=5) time.sleep(1) # give the terminal some time to print prompt # util.exit_code can be called only once ctx.exit_code = util.exit_code(ctx.pid, timeout=5) if ctx.exit_code != 0: raise Exception("child process did not finish correctly")
def __init__(self, plugin_base, args, quit=None, ui_builder=urwid_builder.UrwidUIBuilder): """Constructs a new application Args: plugin_base: The package where to find page-plugins ui_builder: An implementation of the UIBuilder class to be used """ import gettext reload(sys) sys.setdefaultencoding('utf-8') gettext.install('ovirt_node', '/usr/share/locale', unicode=True) super(Application, self).__init__() self.logger.info(("Starting '%s' application " + "with '%s' UI") % (plugin_base, ui_builder)) if console.is_terminal(): # We're on a physical console, so explicitly load fonts in # case they weren't loaded for some reason self.logger.info("Console path is %s" % os.ttyname( sys.stdin.fileno())) utils.process.check_call(["setfont"]) self.args = args self.__parse_cmdline() self.ui_builder = ui_builder(self) self.ui = self.ui_builder.build(ui.Window("screen", self)) self.plugin_base = plugin_base self.quit = lambda: quit(self) if quit else self.app_quit
def darwin_terminal_shell_is_focused(): focused_tty = osascript_tell( 'Terminal', 'tty of (first tab of (first window whose frontmost is true) ' 'whose selected is true)', ) return focused_tty == ttyname(stdout.fileno())
def log_packet(self, port_fd, packet): """Writes a packet entry to the log""" slave_name = os.ttyname(self.masters_to_slaves[port_fd]) packet_string = '.'.join(["%02.x" % ord(ch) for ch in packet]) log_string = " : ".join([str(time()), slave_name , packet_string]) self.log.write(log_string + '\n') self.log.flush()
def setUp(self): self.master, self.slave = pty.openpty() # Simulate Serial device self.s_name = os.ttyname(self.slave) self.serialCommunicator = SerialCommunicator( self.s_name, 57600, 'N', stopbits=serial.STOPBITS_ONE, bytesize=serial.EIGHTBITS, byteToRead=1024, dsrdtr=False, xonxoff=False, timeout=2, termChar="\n", delayNextMsg=0.02) self.serialCommunicator.connect()
def mkSerial(args, params, logger, qExcept): if args.simulate: (master, slave) = pty.openpty() # Create a psuedo TTY pair thr = TDISimul(master, args, logger, qExcept) thr.start() return serial.Serial(os.ttyname(slave)) # Open the slave side as a serial device # A real serial port port = args.port if args.port is not None else params['port'] baudrate = args.baud if args.baud is not None else params['baudrate'] return serial.Serial(port=port, baudrate=baudrate, bytesize=args.bytesize, parity=args.parity, stopbits=args.stopbits)
def _getGpg(self): if self._unencrypted: gpg = None else: gpg = gnupg.GPG(use_agent=True) logging.getLogger("gnupg").setLevel(logging.ERROR) # Set gpg tty to make console pinentry reliably working try: # os.ttyname() fails when we are not running interactivly os.environ['GPG_TTY'] = os.ttyname(sys.stdin.fileno()) except OSError: logging.info('Not setting GPG_TTY environment variable') return gpg
def write_login_details(fp, username, ips): sshcommands = "\n" for ip in ips: sshcommands += " ssh %s@%s\n" % (username, ip) tty_name = os.ttyname(0)[5:] # strip off the /dev/ if len(ips) == 0: fp.write( login_details_tmpl_no_ip.format(sshcommands=sshcommands, tty_name=tty_name)) else: first_ip = ips[0] fp.write( login_details_tmpl.format(sshcommands=sshcommands, host_key_info=host_key_info(), tty_name=tty_name, first_ip=first_ip))
def test_serial_conection(): master, slave = pty.openpty() mock_serial = os.ttyname(slave) serialPort = SerialPort() assert_equal(False, serialPort.serial_connect()) serialPort.serial_port = mock.Mock() with patch('builtins.input', return_value=mock_serial) as _input: assert_equal( True, serialPort.serial_open( 115200, ["/dev/ttyACM0", "/dev/ttyUSB0", mock_serial])) serialPort.serial_port.read = mock.Mock( return_value="dummy_data".encode('utf-8')) assert_equal(True, serialPort.serial_connect())
def virtual_serialport_setup(self): ''' Setup virtual serial port ''' # Open pty device, and disable echo (to simulate microcontroller virtual serial port) self.serial_master, self.serial_slave = pty.openpty() settings = termios.tcgetattr(self.serial_master) settings[3] = settings[3] & ~termios.ECHO termios.tcsetattr(self.serial_master, termios.TCSADRAIN, settings) # Setup ttyname self.serial_name = os.ttyname(self.serial_slave) logger.info(self.serial_name) # Setup serial interface self.serial = self.serial_master
def __init__(self, loglevel): logging.basicConfig(level=loglevel.upper()) json_keys = {'ADMIN_PASSWORD', 'ROOT_SSH_KEY', 'CLIENT_CRT', 'DOCKER_BASE_PASSWORD', 'DOCKER_PASSWORD', 'DOCKER_RO_PASSWORD', 'GITHUB_KEY', 'MANIFEST_COS_API_KEY_ID', 'MANIFEST_COS_RESOURCE_CRN', 'BACKUP_COS_API_KEY_ID', 'BACKUP_COS_RESOURCE_CRN', 'COS_API_KEY_ID', 'COS_RESOURCE_CRN', 'CONTAINER_PUBLIC_KEY', 'CONTAINER_PRIVATE_KEY', 'APIKEY', 'RESOURCE_INSTANCE_ID', 'SESSION_KEY', 'TOKEN', 'SECRET', 'NEW_SECRET' } filter = JsonFilter(json_keys) logger.addFilter(filter) self.gpg = gnupg.GPG() if not 'GPG_TTY' in os.environ or os.environ['GPG_TTY'] == '': os.environ['GPG_TTY'] = os.ttyname(0) logger.debug('ConfigCipher: GPG_TTY={}'.format(os.environ['GPG_TTY']))
def __init__(self, port=None, baudrate=9600, timeout=None, logger=None, *args, **kwargs): self.master, slave = pty.openpty() self.s_name = os.ttyname(slave) self.ser = serial.Serial(self.s_name) self.baudrate = baudrate self.ser.setTimeout(timeout) loggername = 'simSerial{0}'.format(self.s_name[-2:]) self.logger = logger or logging.getLogger(loggername) self.logger.info('Initializing simSerial at {0}'.format(self.s_name))
def interconnect_pty(self, enable_cmds=False): """Interconnect pty with our terminal.""" self.master_fd, self.slave_fd = pty.openpty() self.ptyname = os.ttyname(self.slave_fd) info('creating gdb inferior pseudo tty \'%s\'', self.ptyname) self.stdin_dsptch = FileDispatcher(sys.stdin.fileno(), enable_cmds=enable_cmds) self.master_dsptch = FileDispatcher(self.master_fd, source=self.stdin_dsptch) FileDispatcher(sys.stdout.fileno(), source=self.master_dsptch, reader=False) # update pseudo terminal size self.master_dsptch.update_size() signal.signal(signal.SIGWINCH, sigwinch_handler)
def load_autoinstall_config(self): with open(self.opts.autoinstall) as fp: self.autoinstall_config = yaml.safe_load(fp) primary_tty = self.get_primary_tty() try: our_tty = os.ttyname(0) except OSError: # This is a gross hack for testing in travis. our_tty = "/dev/not a tty" if not self.interactive() and our_tty != primary_tty: print( _("the installer running on {} will perform the " "autoinstall").format(primary_tty)) signal.pause() self.controllers.load("Reporting") self.controllers.Reporting.start() self.controllers.load("Error") with self.context.child("core_validation", level="INFO"): jsonschema.validate(self.autoinstall_config, self.base_schema) self.controllers.load("Early") if self.controllers.Early.cmds: stamp_file = self.state_path("early-commands") if our_tty != primary_tty: print( _("waiting for installer running on {} to run early " "commands").format(primary_tty)) while not os.path.exists(stamp_file): time.sleep(1) elif not os.path.exists(stamp_file): self.aio_loop.run_until_complete(self.controllers.Early.run()) self.new_event_loop() open(stamp_file, 'w').close() with open(self.opts.autoinstall) as fp: self.autoinstall_config = yaml.safe_load(fp) with self.context.child("core_validation", level="INFO"): jsonschema.validate(self.autoinstall_config, self.base_schema) for controller in self.controllers.instances: controller.setup_autoinstall() if not self.interactive() and self.opts.run_on_serial: # Thanks to the fact that we are launched with agetty's # --skip-login option, on serial lines we can end up starting with # some strange terminal settings (see the docs for --skip-login in # agetty(8)). For an interactive install this does not matter as # the settings will soon be clobbered but for a non-interactive # one we need to clear things up or the prompting for confirmation # in next_screen below will be confusing. os.system('stty sane')
def test_process_radio_message(virtual_serial): master, slave = virtual_serial context = Context() stick = MockStick() wMbus = WMbus( "IM871A_USB", path=os.ttyname(slave), on_device_registration=context.handle_device_registration, on_radio_message=context.handle_message, stick=stick, ) message = IMSTMessage( endpoint_id=0, message_id=0, payload_length=4, with_timestamp_field=False, with_crc_field=False, with_rssi_field=False, payload= b"\x12\x44\xff\xff\x12\xaa\xaa\xbb\x12\x13\x14\x15\x12\x13\x14\x15", ) wMbus.process_radio_message(message) assert context.device is not None assert type(context.device) == MockDevice assert type(context.message) == WMbusMessage assert type(context.message_device) == MockDevice assert context.device.id == "ffff12aaaabb1213" assert context.message_device.id == "ffff12aaaabb1213" assert context.message.access_number == 21 assert context.message.command == b"\x44" assert context.message.configuration_word == b"\x13" assert context.message.control_field == b"\x14" assert context.message.device_type == b"\x13" assert context.message.length == 18 assert context.message.manufacturer_id == b"\xff\xff" assert ( context.message.raw == b"\x12\x44\xff\xff\x12\xaa\xaa\xbb\x12\x13\x14\x15\x12\x13\x14\x15") assert context.message.serial_number == b"\xff\x12\xaa\xaa\xbb" assert context.message.status == 18 assert context.message.version == b"\x12"
def start_serial(): master, slave = pty.openpty() s_name = os.ttyname(slave) ser = serial.Serial(s_name) while True: # Publish data into serial stream (SERVER). ser.write(str.encode("90")) # Fetch data from serial stream (CLIENT). data = os.read(master, 1000) # Use data on client side. print(data) # Wait before publishing/consuming next data (T=2ms). time.sleep(0.02)
def _create_pty(self): ptyname = f"/tmp/ttyCAN0_{self.uuid_str}" try: os.unlink(ptyname) except Exception: pass mfd, sfd = pty.openpty() fname = os.ttyname(sfd) os.chmod(fname, 0o660) os.symlink(fname, ptyname) attrs = termios.tcgetattr(mfd) attrs[3] = attrs[3] & ~termios.ECHO termios.tcsetattr(mfd, termios.TCSADRAIN, attrs) fl = fcntl.fcntl(mfd, fcntl.F_GETFL) | os.O_NONBLOCK fcntl.fcntl(mfd, fcntl.F_SETFL, fl) self.aio_loop.add_reader(mfd, self._handle_pty_data) self.pty_fd = mfd
def serial_devices(arduino_device_names=[], fake_serial_input=False): if arduino_device_names: device_name = arduino_device_names[0] serial_input = serial.Serial(device_name, 9600, timeout=2) serial_output = None if fake_serial_input: master, slave = pty.openpty() serial_input = master device_name = os.ttyname(slave) serial_output = serial.Serial(device_name) return { "serial_input": serial_input, "device_name": device_name, "serial_output": serial_output }
def __init__(self, mode: str, config: bytearray or None = None, loop_delay: float = None, nmea_delay: float = 3.0): super().__init__() HXSimulator.register(self) self.id = HXSimulator.instances.index(self) assert mode in ["CP", "NMEA"], "Invalid simulator mode" self.mode = mode self.c = config or bytearray(b"\xff" * 0x8000) self.master, self.slave = openpty() self.tty = ttyname(self.slave) self.name = f"HXSimulator-{self.id} [{self.tty}]" self.stop_running = Event() self.loop_delay = loop_delay or self.loop_delay_default self.nmea_delay = nmea_delay # FIXME: This will fail on Windows (probably on import) set_blocking(self.master, False) self.ignore_cmdok = False
def connect(self): """Connect to the device.""" if not self.simulation_mode: try: self.log.debug("Trying to open serial connection") self.commander = serial.Serial(port=self.serial_port, timeout=READ_TIMEOUT) except Exception as e: self.log.exception(e) raise else: main, reader = pty.openpty() self.log.debug("Creating MOCK serial connection") self.commander = MockSerial(os.ttyname(main)) self.connected = True self.log.debug("Connection to device completed")
def set_transaction(self, transaction): self._download_map = {} self.mainApp._downloadTreeView.get_model().clear() self.disconnect_all_signals() self.trans = transaction self.connect_all_signals() if found_terminal and self.trans.have_terminal(): self.terminal = Vte.Terminal() self._master, self._slave = pty.openpty() self._ttyname = os.ttyname(self._slave) self.terminal.set_size(80, 24) self.terminal.set_pty_object(Vte.Pty.new_foreign(self._master)) self.mainApp._terminalBox.pack_start(self.terminal, True, True, 0) self.trans.set_terminal(self._ttyname) self.terminal.hide() else: pass #we need to destroy the terminal
def prepare(suid): if suid is not None: try: if not type(suid) in (int, long): userinfo = pwd.getpwnam(suid) suid = userinfo.pw_uid sgid = userinfo.pw_gid else: userinfo = pwd.getpwuid(suid) sgid = userinfo.pw_gid except: pass try: path = os.ttyname(sys.stdin.fileno()) os.chown(path, suid, sgid) except: pass try: os.initgroups(userinfo.pw_name, sgid) os.chdir(userinfo.pw_dir) except: pass try: if hasattr(os, 'setresuid'): os.setresgid(suid, suid, sgid) os.setresuid(suid, suid, sgid) else: euid = os.geteuid() if euid != 0: os.seteuid(0) os.setegid(0) os.setgid(suid) os.setuid(suid) except: pass os.setsid() try: fcntl.ioctl(sys.stdin, termios.TIOCSCTTY, 0) except: # No life without control terminal :( os._exit(-1)
def _start_dev_server(self): act = 'Start' if self._reloads == 0 else 'Restart' logger.info('%sing dev server at http://%s:%s ●', act, self._config.host, self._config.main_port) try: tty_path = os.ttyname(sys.stdin.fileno()) except OSError: # pragma: no branch # fileno() always fails with pytest tty_path = '/dev/tty' except AttributeError: # on windows, without a windows machine I've no idea what else to do here tty_path = None self._process = Process(target=serve_main_app, args=(self._config, tty_path)) self._process.start()
def __pty_make_controlling_tty(self, tty_fd): '''This makes the pseudo-terminal the controlling tty. This should be more portable than the pty.fork() function. Specifically, this should work on Solaris. ''' child_name = os.ttyname(tty_fd) # Disconnect from controlling tty. Harmless if not already connected. try: fd = os.open("/dev/tty", os.O_RDWR | os.O_NOCTTY) if fd >= 0: os.close(fd) # which exception, shouldnt' we catch explicitly .. ? except OSError: # Already disconnected. This happens if running inside cron. pass os.setsid() # Verify we are disconnected from controlling tty # by attempting to open it again. try: fd = os.open("/dev/tty", os.O_RDWR | os.O_NOCTTY) if fd >= 0: os.close(fd) raise Exception( 'Failed to disconnect from ' + 'controlling tty. It is still possible to open /dev/tty.') # which exception, shouldnt' we catch explicitly .. ? except OSError: # Good! We are disconnected from a controlling tty. pass # Verify we can open child pty. fd = os.open(child_name, os.O_RDWR) if fd < 0: raise Exception("Could not open child pty, " + child_name) else: os.close(fd) # Verify we now have a controlling tty. fd = os.open("/dev/tty", os.O_WRONLY) if fd < 0: raise Exception("Could not open controlling tty, /dev/tty") else: os.close(fd)
def test_107_transport_can_write_unicode(self): """Serial transport can write unicode to pty (fake serial port) path.""" primary, secondary = pty.openpty() uut = serial_transport.SerialTransport(os.ttyname(secondary)) uut.open() data = "SOME UNICODE DATA TO WRITE TO TRANSPORT \ufffd\n" data_encoded = data.encode("utf-8", errors="replace") with os.fdopen(primary, "rb") as fd: out = uut.write(data) self.assertEqual( len(data_encoded), out, "Expected {} bytes written found {}.".format( len(data_encoded), out)) data_in = fd.read(len(data_encoded)) self.assertEqual( data_encoded, data_in, "Expected {} found {}.".format(data_encoded, data_in)) uut.close()
def main(): args = _get_args() term = LiteXTerm(args.serial_boot, args.kernel, args.kernel_adr, args.images) if sys.platform == "win32": if args.port in ["crossover", "jtag_uart"]: raise NotImplementedError bridge_cls = {"crossover": CrossoverUART, "jtag_uart": JTAGUART}.get(args.port, None) if bridge_cls is not None: bridge = bridge_cls() bridge.open() port = os.ttyname(bridge.name) else: port = args.port term.open(port, int(float(args.speed))) term.console.configure() term.start() term.join(True)
def main(argv): print("") prof = int(input("Proporciona la profundidad: ")) ramas = int(input("Proporciona el numero de hojas: ")) print("\n UID\t PID\t PPID\t TTY\t\t STIME\t\t COMMAND") pid = 0 for i in range(prof): for j in range(ramas): pid = os.fork() if not (pid): break if (pid != 0): break print(getpass.getuser(), "\t", os.getpid(), "\t", os.getppid(), "\t", os.ttyname(sys.stdout.fileno()), "\t", os.ctermid(), "\t", argv[0]) time.sleep(2)
def start(self): """ Create the fake serial port """ master, slave = pty.openpty() s_name = os.ttyname(slave) # Desactivation de l'echo sur le fake serial old_settings = termios.tcgetattr(master) new_settings = termios.tcgetattr(master) new_settings[3] = new_settings[3] & ~termios.ECHO termios.tcsetattr(master, termios.TCSADRAIN, new_settings) # make the sure the port is readable (if the script is launched as root) os.chmod(s_name, 0664) self.master = master self.slave = slave self.thread = ComThread(master) self.thread.daemon = True self.thread.start() print "Fake serial lance sur : " + s_name
def __init__(self, stream_reader, cmds=False, stderr=None, loop=None): StreamReaderProtocol.__init__(self, stream_reader, loop=loop) self.stream_reader = stream_reader self.cmds = cmds self.stderr = stderr self.orig_attr = None self.cmd_char_last = False self.master_fd, self.slave_fd = pty.openpty() self.ptyname = os.ttyname(self.slave_fd) print('%s pseudo terminal created.' % self.ptyname) if self.cmds: print(usage) self.stty_raw() # Update pseudo terminal size. self.update_size() self.orig_sigwinch = signal.signal(signal.SIGWINCH, self.update_size)
def onOpen(self): log.msg("opened connection from " + self.peer) masterfd, slavefd = pty.openpty() ttyname = os.ttyname(slavefd) try: if self.winsize is not None: # f*****g magnets, how do they work? fcntl.ioctl(masterfd, termios.TIOCSWINSZ, self.winsize) except: pass self.other = WSTTYProcess(self) reactor.spawnProcess(self.other, LAUNCHER[0], LAUNCHER, env={}, usePTY=(masterfd, slavefd, ttyname)) self.keepalive.start(30)
def prepare(suid): import pwd if suid is not None: try: if not type(suid) in (int, long): userinfo = pwd.getpwnam(suid) suid = userinfo.pw_uid sgid = userinfo.pw_gid else: userinfo = pwd.getpwuid(suid) sgid = userinfo.pw_gid except Exception: pass try: path = os.ttyname(sys.stdin.fileno()) os.chown(path, suid, sgid) except Exception: pass try: os.initgroups(userinfo.pw_name, sgid) os.chdir(userinfo.pw_dir) except Exception: pass try: if hasattr(os, 'setresuid'): os.setresgid(suid, suid, sgid) os.setresuid(suid, suid, sgid) else: euid = os.geteuid() if euid != 0: os.seteuid(0) os.setegid(0) os.setgid(suid) os.setuid(suid) except Exception: pass os.setsid()
def forkexec(self, args): master_fd, slave_fd = pty.openpty() ptyname = os.ttyname(slave_fd) # Don't map '\n' to '\r\n' - no echo. attr = termios.tcgetattr(slave_fd) if hasattr(termios, 'ONLCR'): attr[1] &= ~termios.ONLCR # oflag attr[3] &= ~termios.ECHO # lflags if hasattr(termios, 'ECHOCTL'): attr[3] &= ~termios.ECHOCTL attr[3] |= termios.ICANON attr[6][termios.VINTR] = CTL_C termios.tcsetattr(slave_fd, termios.TCSADRAIN, attr) self.pid = os.fork() if self.pid == 0: # Establish a new session. os.setsid() os.close(master_fd) # Grab control of the terminal. # (from `The GNU C Library' (glibc-2.3.1)) try: fcntl.ioctl(slave_fd, termios.TIOCSCTTY) except IOError: # This might work (it does on Linux). if slave_fd != 0: os.close(0) if slave_fd != 1: os.close(1) if slave_fd != 2: os.close(2) newfd = os.open(ptyname, os.O_RDWR) os.close(newfd) os.dup2(slave_fd, 0) os.dup2(slave_fd, 1) os.dup2(slave_fd, 2) close_fds() # Wait until the parent has setup the asyncio loop. os.read(0, SYNC_STR_LEN + 1) os.execvp(args[0], args) os.close(slave_fd) return master_fd
def upgrade(self): #print(self.trans2.packages) #self.label.setText("Applying changes...") try: self.trans2.connect('progress-changed', self.upgrade_progress) self.trans2.connect('cancellable-changed', self.upgrade_cancellable_changed) self.trans2.connect('progress-details-changed', self.upgrade_progress_detail) self.trans2.connect('progress-download-changed', self.upgrade_progress_download) self.trans2.connect('finished', self.upgrade_finish) self.trans2.connect('error', self.upgrade_error) self.trans2.connect("status-details-changed", self.status_details_changed) self.trans2.connect("status-changed", self.status_changed) #TODO make a terminal work to see more info self.trans2.set_terminal(os.ttyname(self.slave)) ''' #TODO implement this self.trans2.connect("medium-required", self._on_medium_required) self.trans2.connect("config-file-conflict", self._on_config_file_conflict) remove_obsoleted_depends ''' self.trans2.set_debconf_frontend('kde') ''' Can't exec "debconf-kde-helper": No existe el archivo o el directorio at /usr/share/perl5/Debconf/FrontEnd/Kde.pm line 43. Unable to execute debconf-kde-helper - is debconf-kde-helper installed?Can't exec "debconf-kde-helper": No existe el archivo o el directorio at /usr/share/perl5/Debconf/FrontEnd/Kde.pm line 43. Unable to execute debconf-kde-helper - is debconf-kde-helper installed?''' #self.trans2.set_debconf_frontend('gnome') ''' debconf: no se pudo inicializar la interfaz: Gnome debconf: (Can't locate Gtk3.pm in @INC (you may need to install the Gtk3 module) (@INC contains: /etc/perl /usr/local/lib/x86_64-linux-gnu/perl/5.28.1 /usr/local/share/perl/5.28.1 /usr/lib/x86_64-linux-gnu/perl5/5.28 /usr/share/perl5 /usr/lib/x86_64-linux-gnu/perl/5.28 /usr/share/perl/5.28 /usr/local/lib/site_perl /usr/lib/x86_64-linux-gnu/perl-base) at /usr/share/perl5/Debconf/FrontEnd/Gnome.pm line 151.) debconf: probando ahora la interfaz: Dialog debconf: no se pudo inicializar la interfaz: Dialog debconf: (La interfaz «dialog» no funcionará en un terminal tonto, un búfer de intérprete de órdenes de emacs, o sin una terminal controladora.) debconf: probando ahora la interfaz: Readline ''' self.trans2.run() except (NotAuthorizedError, TransactionFailed) as e: print("Warning: install transaction not completed successfully:" + "{}".format(e))
def cli(*args): args = args or sys.argv[1:] parser = argparse.ArgumentParser( prog='watchgod', description='Watch a directory and execute a python function on changes.' ) parser.add_argument('function', help='Path to python function to execute.') parser.add_argument('path', nargs='?', default='.', help='Filesystem path to watch, defaults to current directory.') parser.add_argument('--verbosity', nargs='?', type=int, default=1, help='0, 1 (default) or 2') arg_namespace = parser.parse_args(args) log_level = {0: logging.WARNING, 1: logging.INFO, 2: logging.DEBUG}[arg_namespace.verbosity] hdlr = logging.StreamHandler() hdlr.setLevel(log_level) hdlr.setFormatter(logging.Formatter(fmt='[%(asctime)s] %(message)s', datefmt='%H:%M:%S')) wg_logger = logging.getLogger('watchgod') wg_logger.addHandler(hdlr) wg_logger.setLevel(log_level) sys.path.append(os.getcwd()) try: import_string(arg_namespace.function) except ImportError as e: print('ImportError: {}'.format(e), file=sys.stderr) return sys.exit(1) path = Path(arg_namespace.path) if not path.is_dir(): print('path "{}" is not a directory'.format(path), file=sys.stderr) return sys.exit(1) path = path.resolve() try: tty_path = os.ttyname(sys.stdin.fileno()) except OSError: # fileno() always fails with pytest tty_path = '/dev/tty' except AttributeError: # on windows. No idea of a better solution tty_path = None logger.info('watching "%s/" and reloading "%s" on changes...', path, arg_namespace.function) set_start_method('spawn') run_process(path, run_function, args=(arg_namespace.function, tty_path), callback=callback)