Ejemplo n.º 1
0
    def __call__(self, path):

        path = expanduser(path)

        if path == '/dev/stdout' and 'a' in self.mode:

            self.mode = self.mode.replace('a', 'w')

        if path == '-':

            if 'r' in self.mode:
                file_obj = stdin.buffer if 'b' in self.mode else stdin
            else:
                file_obj = fdopen(dup(stdout.fileno()),
                                  'wb' if 'b' in self.mode else 'w')
                dup2(stderr.fileno(), stdout.fileno())
            return file_obj

        elif path[-3:] != '.gz':

            file_obj = open(path, self.mode)

        else:

            file_obj = gzip.open(path, {
                'r': 'rt',
                'a': 'at'
            }.get(self.mode, self.mode))

        file_obj.appending_to_file = bool(exists(path) and getsize(path))

        return file_obj
Ejemplo n.º 2
0
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
Ejemplo n.º 3
0
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])
Ejemplo n.º 4
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)
Ejemplo n.º 5
0
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())
Ejemplo n.º 6
0
 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()
Ejemplo n.º 7
0
   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()
Ejemplo n.º 8
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(优先级别高)
Ejemplo n.º 9
0
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())
Ejemplo n.º 10
0
def parse_args():
    p = argparse.ArgumentParser(description='Create a git repository with the history of the specified Wikipedia article.')
    p.add_argument('article_name')
    p.add_argument('-n', '--no-import', dest='doimport', default=True, action='store_false',
                   help="Don't invoke git fast-import; only generate fast-import data stream")
    p.add_argument('-o', '--out', help='Output directory or fast-import stream file')
    g=p.add_mutually_exclusive_group()
    g.add_argument('--lang', default=lang, help='Wikipedia language code (default %(default)s)')
    g.add_argument('--site', help='Alternate site (e.g. http://commons.wikimedia.org[/w/])')

    args = p.parse_args()
    if not args.doimport:
        if args.out is None:
            # http://stackoverflow.com/a/2374507/20789
            if platform == "win32":
                import os, msvcrt
                msvcrt.setmode(stdout.fileno(), os.O_BINARY)
            args.out = stdout
        else:
            try:
                args.out = argparse.FileType('wb')(args.out)
            except argparse.ArgumentTypeError as e:
                p.error(e.args[0])

    return p, args
Ejemplo n.º 11
0
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])
Ejemplo n.º 12
0
def wait(index=0,
         sleep_time=0.25,
         symbols=['→', '↘', '↓', '↙', '←', '↖', '↑', '↗'],
         text=""):
    width = unpack('HH', ioctl(stdout.fileno(), TIOCGWINSZ, '0000'))[1]
    stdout.write('\r%s %s%s' % (text, symbols[index], ' ' *
                                (width - len(text) - 3)))
    stdout.flush()
    sleep(sleep_time)
    return (index + 1) % len(symbols)
Ejemplo n.º 13
0
    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))
Ejemplo n.º 14
0
    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))
Ejemplo n.º 15
0
def extractlayers(dc, args, layers, top_most_layer_id):
    target_path = args.target
    flags = O_WRONLY

    if target_path == _TARGET_STDOUT:
        target_fd = stdout.fileno()
    else:
        flags |= O_CREAT | O_TRUNC

        if not args.force:
            flags |= O_EXCL

        target_fd = logexception(
            _LOGGER, ERROR,
            'unable to open target file "{}": {{e}}'.format(target_path),
            os_open, target_path, flags, 0o666)

    with fdopen(target_fd, 'wb') as target_file:
        if hasattr(target_file, 'seekable'):
            seekable = target_file.seekable()
        else:
            try:
                seekable = not lseek(target_fd, 0, SEEK_CUR) < 0 \
                    and S_ISREG(fstat(target_fd).st_mode)
            except OSError as e:
                if errorcode.get(e.errno) != 'ESPIPE':
                    raise

                seekable = False

        open_args = {'fileobj': target_file}

        if args.compression is None:
            open_args['mode'] = 'w' if seekable else 'w|'
        else:
            if seekable:
                mode = 'w:{}'
                open_args['compresslevel'] = args.compress_level
                _, ext = ospath_splitext(target_path)

                if ext.lower() != '{}{}'.format(ospath_extsep,
                                                args.compression):
                    _LOGGER.warning(
                        'target name "%s" doesn\'t match compression type ("%s")',
                        target_path, args.compression)
            else:
                mode = 'w|{}'
                _LOGGER.warning(
                    'target "%s" is not seekable, ignoring compression level (%d)',
                    target_path, args.compress_level)

            open_args['mode'] = mode.format(args.compression)

        with tarfile_open(**open_args) as tar_file:
            dimgx_extractlayers(dc, layers, tar_file, top_most_layer_id)
Ejemplo n.º 16
0
def read_data(cmd_txt, parm,  server_addr, fname, skip, get):
    res = b""
    try:
        s = socket()
        s.settimeout(5)
        s.connect(server_addr)
        if s:
# pack & send command
            cmd = cmd_txt + parm
            cmd = pack("<l%ds" % len(cmd), len(cmd), cmd.encode())
            s.send(cmd)
# get length of response
            ss = s.recv(4)
            size = unpack("<l", ss)[0]
# skip header
            hdr_size = len(cmd_txt) + 4
            name = s.recv(hdr_size) 
#            stderr.write("Command %s, parm %s, Size %d, Header_size %d\n" % (cmd_txt, parm, size, hdr_size))
            size -= hdr_size
# open file, if required
            if fname != None:
                if fname:
                    f = open(fname, "wb")
                else:
                    f = fdopen(stdout.fileno(), 'wb') # binary stdout
# if additional skip, do it
            while skip > 0:
                img = s.recv(min(skip, 4096))
                size -= len(img)
                skip -= len(img)
# check, whether not the full data is required
            if get > 0 and get < size:
                skip = size - get
                size = get
# get bulk data
            while size > 0:
                img = s.recv(min(size, 4096))
                if fname != None:
                    f.write(img)
                else:
                    res += img
                size -= len(img)
# eat up what's left                
            while skip > 0:
                img = s.recv(min(skip, 4096))
                skip -= len(img)
# and that's it
            if fname:
                f.close()
            s.close()
            return res
    except Exception as err:
        stderr.write("Error attempting to get data, reason: %s\n" % err)
        return False
Ejemplo n.º 17
0
 def __init__(self, device, baudrate=115200, logfile=None, debug=False):
     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
Ejemplo n.º 18
0
Archivo: utils.py Proyecto: nbstar/dxr
def open_log(folder, name, use_stdout=False):
    """Return a writable file-like object representing a log file.

    :arg folder: The folder to put the log file in
    :arg name: The name of the log file
    :arg use_stdout: If True, return a handle to stdout for verbose output,
        duplicated so it can be closed with impunity.

    """
    if use_stdout:
        return fdopen(dup(stdout.fileno()), 'w')
    return open(join(folder, name), 'w', 1)
Ejemplo n.º 19
0
def open_log(folder, name, use_stdout=False):
    """Return a writable file-like object representing a log file.

    :arg folder: The folder to put the log file in
    :arg name: The name of the log file
    :arg use_stdout: If True, return a handle to stdout for verbose output,
        duplicated so it can be closed with impunity.

    """
    if use_stdout:
        return fdopen(dup(stdout.fileno()), 'w')
    return open(join(folder, name), 'w', 1)
Ejemplo n.º 20
0
def open_log(config_or_tree, name, use_stdout=False):
    """Return a writable file-like object representing a log file.

    :arg config_or_tree: a Config or Tree object which tells us which folder to
        put the log file in
    :arg name: The name of the log file
    :arg use_stdout: If True, return a handle to stdout for verbose output,
        duplicated so it can be closed with impunity.

    """
    if use_stdout:
        return os.fdopen(dup(stdout.fileno()), 'w')
    return open(os.path.join(config_or_tree.log_folder, name), 'w', 1)
Ejemplo n.º 21
0
 def redirect_file_descriptors(
     daemon_stdin='/dev/null',
     daemon_stdout='/dev/null',
     daemon_stderr='/dev/null',
 ):
     for file_descriptor in [stdout, stderr]:
         file_descriptor.flush()
     new_stdin = open(daemon_stdin, 'r')
     new_stdout = open(daemon_stdout, 'a+')
     new_stderr = open(daemon_stderr, 'a+')
     dup2(new_stdin.fileno(), stdin.fileno())
     dup2(new_stdout.fileno(), stdout.fileno())
     dup2(new_stderr.fileno(), stderr.fileno())
Ejemplo n.º 22
0
 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())
Ejemplo n.º 23
0
 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())
Ejemplo n.º 24
0
def open_log(config_or_tree, name, use_stdout=False):
    """Return a writable file-like object representing a log file.

    :arg config_or_tree: a Config or Tree object which tells us which folder to
        put the log file in
    :arg name: The name of the log file
    :arg use_stdout: If True, return a handle to stdout for verbose output,
        duplicated so it can be closed with impunity.

    """
    if use_stdout:
        return os.fdopen(dup(stdout.fileno()), 'w')
    return open(os.path.join(config_or_tree.log_folder, name), 'w', 1)
Ejemplo n.º 25
0
def main():
    """Get command-line arguments and output results in specified formats"""
    args = cli(argv[0])
    excluded_network_list = args.excluded_network_list
    inclusive_netlist = exclude_nets_to_include_nets(excluded_network_list,
                                                     strict=args.strict)

    if args.no_ip6 is False:
        inclusive_netlist.append(ip_network_safe(IPV6_ALL_NET))

    csv_inclusive_netlist = ','.join(
        [included_net.compressed for included_net in inclusive_netlist])

    if args.enable_lines:
        output('')
        output('Line-based output:')
        for included_net in [net.compressed for net in inclusive_netlist]:
            output('{}'.format(included_net))

    if args.disable_csv is False:
        output('')
        output('{}{}'.format(
            'AllowedIPs = ' if args.wireguard_format is True else '',
            csv_inclusive_netlist))

    if args.qrencode is True:
        output('')
        if QRCode is not None:
            output('Generating QR code using Python QRCode()')
            output('========================================\n')
            qr = QRCode(error_correction=ERROR_CORRECT_M)
            qr.add_data(csv_inclusive_netlist)
            if isatty(stdout.fileno()):
                qr.print_ascii(tty=True)
                return
            fatal('Must have an allocated TTY to generate QR code!')
        else:
            output('Generating QR code using qrencode -t ansi')
            output('========================================\n')
            qr_encode_command = QR_ENCODE_COMMAND + [csv_inclusive_netlist]
            output('Generating WireGuard friendly QR code format:')
            try:
                result = run(qr_encode_command, stdout=PIPE, check=True)
            except CalledProcessError as err:
                fatal('failed to invoke `qrencode` app ({})'.format(err))
            output(result.stdout.decode('utf-8'))
            output('')
    else:
        output(
            'NOTE: Consider using `--qr` to generate a QR code on your terminal!'
        )
Ejemplo n.º 26
0
Archivo: cli.py Proyecto: pilona/RPN
    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
Ejemplo n.º 27
0
def sudo(command):
    """do shell "%s" with administrator privileges
    http://developer.apple.com/library/mac/#technotes/tn2065/_index.html"""
    if isatty(stdout.fileno()): # terminal
        cmd="sudo %s" % command
        r=run(cmd)
    else: # GUI
        escaped=command.replace('"','\\"')
        cmd='do shell script "%s" with administrator privileges' % escaped
        r=run("osascript",cmd)
    if r.status_code==0:
        return r.std_out
    else:
        raise Exception(r.std_err)
Ejemplo n.º 28
0
    def execute_in_background(self):
        '''
        Executes tasks that do involve background execution.
        '''

        #Fork a process for the child to run

        process = os.fork()
        if process != 0:  #If parent just return to main thread (back to shell get input)
            return

        #Printing the PID of the background proccess is really useful in case user needs to kill it

        print('\r\r[' + str(os.getpid()) + ']         ')

        if self.is_internal:

            #If it's internal just run the command by calling the function.

            self.task(self.args, out=self.output)
            print('\r[' + str(os.getpid()) +
                  '] done')  #Let the user know proccess finished
            exit(0)
        else:

            secondary = os.fork()

            # we fork a second process to monitor it's child which will run the program in the background.
            # this is essential as we have no way of knowing when the child process is done otherwise.

            if secondary != 0:
                self.wait_for_finish(
                )  #Wait for the child process to finish and notify user.
            else:

                #flush the standard input, output and error

                stderr.flush()
                stdout.flush()
                stdin.flush()

                # we check for IO redirection streams other to stdin, stdout and if so duplicate the file handler below.

                if self.input != stdin:
                    os.dup2(self.input.fileno(), stdin.fileno())  #stdin
                if self.output != stdout:
                    os.dup2(self.output.fileno(), stdout.fileno())  #stdout

                os.execv(self.task, [self.task] + self.args)  #execute task
Ejemplo n.º 29
0
def extractlayers(dc, args, layers, top_most_layer_id):
    target_path = args.target
    flags = O_WRONLY

    if target_path == _TARGET_STDOUT:
        target_fd = stdout.fileno()
    else:
        flags |= O_CREAT | O_TRUNC

        if not args.force:
            flags |= O_EXCL

        target_fd = logexception(_LOGGER, ERROR, 'unable to open target file "{}": {{e}}'.format(target_path), os_open, target_path, flags, 0o666)

    with fdopen(target_fd, 'wb') as target_file:
        if hasattr(target_file, 'seekable'):
            seekable = target_file.seekable()
        else:
            try:
                seekable = not lseek(target_fd, 0, SEEK_CUR) < 0 \
                    and S_ISREG(fstat(target_fd).st_mode)
            except OSError as e:
                if errorcode.get(e.errno) != 'ESPIPE':
                    raise

                seekable = False

        open_args = { 'fileobj': target_file }

        if args.compression is None:
            open_args['mode'] = 'w' if seekable else 'w|'
        else:
            if seekable:
                mode = 'w:{}'
                open_args['compresslevel'] = args.compress_level
                _, ext = ospath_splitext(target_path)

                if ext.lower() != '{}{}'.format(ospath_extsep, args.compression):
                    _LOGGER.warning('target name "%s" doesn\'t match compression type ("%s")', target_path, args.compression)
            else:
                mode = 'w|{}'
                _LOGGER.warning('target "%s" is not seekable, ignoring compression level (%d)', target_path, args.compress_level)

            open_args['mode'] = mode.format(args.compression)

        with tarfile_open(**open_args) as tar_file:
            dimgx_extractlayers(dc, layers, tar_file, top_most_layer_id)
Ejemplo n.º 30
0
def parse_args():
    """Parses the command line arguments."""
    p = argparse.ArgumentParser(
        description='Create a git repository with the history of the specified Wikipedia article.')
    p.add_argument('article_name')

    output = p.add_argument_group('Output options')
    g = output.add_mutually_exclusive_group()
    g.add_argument('-n', '--no-import', dest='doimport', default=True, action='store_false',
                   help='Don\'t invoke git fast-import; only generate fast-import data stream')
    g.add_argument('-b', '--bare', action='store_true',
                   help='Import to a bare repository (no working tree)')
    output.add_argument('-o', '--out',
                        help='Output directory or fast-import stream file')

    site = p.add_argument_group('MediaWiki site selection')
    g = site.add_mutually_exclusive_group()
    g.add_argument('--lang', default=locale.getdefaultlocale()[0].split('_')[0] or '',
                   help='Wikipedia language code (default %(default)s)')
    g.add_argument('--site',
                   help='Alternate MediaWiki site (e.g. https://commons.wikimedia.org[/w/])')

    revision = p.add_argument_group('Revision options')
    revision.add_argument('--expandtemplates', action='store_true', help='Expand templates')
    revision.add_argument('--start', help='ISO8601 timestamp to start listing from')
    revision.add_argument('--end', help='ISO8601 timestamp to end listing at')
    revision.add_argument('--user', help='Only list revisions made by this user')
    revision.add_argument('--excludeuser', help='Exclude revisions made by this user')

    args = p.parse_args()
    if not args.doimport:
        if args.out is None:
            # https://stackoverflow.com/a/2374507/20789
            if platform == 'win32':
                import msvcrt
                msvcrt.setmode(stdout.fileno(), os.O_BINARY)
            try:
                args.out = stdout.buffer
            except AttributeError:
                args.out = stdout
        else:
            try:
                args.out = argparse.FileType('wb')(args.out)
            except argparse.ArgumentTypeError as e:
                p.error(e.args[0])

    return p, args
Ejemplo n.º 31
0
 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)
Ejemplo n.º 32
0
 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)
Ejemplo n.º 33
0
Archivo: zhk.py Proyecto: ymv/zhk
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()
Ejemplo n.º 34
0
def connect_over_serial(url, baudrate):
    from term import getkey
    from sys import platform, stdin, stdout, stderr
    MSWIN = platform == 'win32'

    if not MSWIN:
        from termios import TCSANOW, tcgetattr, tcsetattr

    if not MSWIN and stdout.isatty():
        termstates = [(fd, tcgetattr(fd))
                      for fd in (stdin.fileno(), stdout.fileno(),
                                 stderr.fileno())]

    from pyftdi.serialext import serial_for_url

    try:
        port = serial_for_url(url, baudrate=baudrate)
    except SerialException as e:
        print("Uh-oh:", e)
        from pyftdi.ftdi import Ftdi

        Ftdi().open_from_url('ftdi:///?')
        sys.exit(1)

    print("Connected.")

    try:
        while True:
            try:
                c = getkey(False)

                if MSWIN and ord(c) == 3:
                    raise KeyboardInterrupt()

                stdout.write(c.decode('utf8', errors='replace'))
                stdout.flush()
                port.write(c)
            except KeyboardInterrupt:
                port.close()
                print("kbai")
                break
    finally:
        for fd, att in termstates:
            tcsetattr(fd, TCSANOW, att)
Ejemplo n.º 35
0
def execute_test(n_controllers, n_loggers):
    """Test function"""
    # Run RUPS
    server = subprocess.Popen([
        path.join(RUPS_BIN), '--noinfo', 'cat', '--bind', '3000', '--logbind',
        '4000'
    ],
                              stdout=stdout.fileno(),
                              stdin=subprocess.PIPE)
    time.sleep(1)

    stimuli = ['Hello world!']
    expected = stimuli[:] + stimuli[:]

    # Run first controller that will output something
    threads = []
    thread = threading.Thread(target=single_controller,
                              args=('3000', stimuli, expected))
    thread.start()
    threads.append(thread)
    # Run the rest of the controllers
    for _ in range(n_controllers - 1):
        thread = threading.Thread(target=single_controller,
                                  args=('3000', None, expected))
        thread.start()
        threads.append(thread)

    # Run loggers
    for _ in range(n_loggers):
        thread = threading.Thread(target=single_logger,
                                  args=('4000', expected))
        thread.start()
        threads.append(thread)

    time.sleep(3)
    print("Sending INTERRUPT to server")
    server.send_signal(signal.SIGINT)
    server.wait()

    for thread in threads:
        thread.join()

    print('Test complete')
Ejemplo n.º 36
0
 def init(self, fullterm: bool) -> None:
     """Internal terminal initialization function"""
     if not self.IS_MSWIN:
         if stdout.isatty():
             self._termstates = [(fd, tcgetattr(fd)) for fd in
                                 (stdin.fileno(), stdout.fileno(),
                                  stderr.fileno())]
         tfd = stdin.fileno()
         new = tcgetattr(tfd)
         new[3] = new[3] & ~ICANON & ~ECHO
         new[6][VMIN] = 1
         new[6][VTIME] = 0
         if fullterm:
             new[6][VINTR] = 0
             new[6][VSUSP] = 0
         tcsetattr(tfd, TCSANOW, new)
     else:
         # Windows black magic
         # https://stackoverflow.com/questions/12492810
         call('', shell=True)
Ejemplo n.º 37
0
def doFork():
  if os.fork(): exit(0)
  os.umask(0)
  os.setsid()
  if os.fork(): exit(0)

  stdout.flush()
  stderr.flush()

  si = os.open('/dev/null')
  so = os.open('/dev/null','w')
  se = os.open('/dev/null','w')

  os.dup2(si.fileno(),stdin.fileno())
  os.dup2(so.fileno(),stdout.fileno())
  os.dup2(se.fileno(),stderr.fileno())

  # drop privs
  # setgid(getgrnam(group).gr_gid)
  # setuid(getpwnam(user).pw_uid)
  os.chdir('/')
Ejemplo n.º 38
0
def doFork():
    if os.fork(): exit(0)
    os.umask(0)
    os.setsid()
    if os.fork(): exit(0)

    stdout.flush()
    stderr.flush()

    si = os.open('/dev/null')
    so = os.open('/dev/null', 'w')
    se = os.open('/dev/null', 'w')

    os.dup2(si.fileno(), stdin.fileno())
    os.dup2(so.fileno(), stdout.fileno())
    os.dup2(se.fileno(), stderr.fileno())

    # drop privs
    # setgid(getgrnam(group).gr_gid)
    # setuid(getpwnam(user).pw_uid)
    os.chdir('/')
Ejemplo n.º 39
0
def parse_args():
    p = argparse.ArgumentParser(
        description=
        'Create a git repository with the history of the specified Wikipedia article.'
    )
    p.add_argument('article_name')
    p.add_argument(
        '-n',
        '--no-import',
        dest='doimport',
        default=True,
        action='store_false',
        help=
        "Don't invoke git fast-import; only generate fast-import data stream")
    p.add_argument('-o',
                   '--out',
                   help='Output directory or fast-import stream file')
    g = p.add_mutually_exclusive_group()
    g.add_argument('--lang',
                   default=lang,
                   help='Wikipedia language code (default %(default)s)')
    g.add_argument(
        '--site',
        help='Alternate site (e.g. http://commons.wikimedia.org[/w/])')

    args = p.parse_args()
    if not args.doimport:
        if args.out is None:
            # http://stackoverflow.com/a/2374507/20789
            if platform == "win32":
                import os, msvcrt
                msvcrt.setmode(stdout.fileno(), os.O_BINARY)
            args.out = stdout
        else:
            try:
                args.out = argparse.FileType('wb')(args.out)
            except argparse.ArgumentTypeError as e:
                p.error(e.args[0])

    return p, args
Ejemplo n.º 40
0
   def daemonize(self):
      '''
      Forks then sets up the I/O stream for the daemon 
      '''
      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.delPID)
      self.setPID()
Ejemplo n.º 41
0
def stopwatch(
    stdscr,
    alt_format=False,
    font=DEFAULT_FONT,
    no_figlet=False,
    no_seconds=False,
    quit_after=None,
    title=None,
    outfile=None,
    no_window_title=False,
    time=False,
    time_format=None,
    **kwargs
):
    curses_lock, input_queue, quit_event = setup(stdscr)
    figlet = Figlet(font=font)

    if title and not no_figlet:
        try:
            title = figlet.renderText(title)
        except CharNotPrinted:
            title = ""

    input_thread = Thread(
        args=(stdscr, input_queue, quit_event, curses_lock),
        target=input_thread_body,
    )
    input_thread.start()

    try:
        sync_start = datetime.now()
        pause_start = None
        seconds_elapsed = 0
        laps = []
        while quit_after is None or seconds_elapsed < int(quit_after):
            figlet.width = stdscr.getmaxyx()[1]
            if time:
                countdown_text = datetime.now().strftime(time_format)
            elif alt_format:
                countdown_text = format_seconds_alt(seconds_elapsed, 0, hide_seconds=no_seconds)
            else:
                countdown_text = format_seconds(seconds_elapsed, hide_seconds=no_seconds)
            with curses_lock:
                if not no_window_title:
                    os.write(stdout.fileno(), "\033]2;{0}\007".format(countdown_text).encode())
                if outfile:
                    with open(outfile, 'w') as f:
                        f.write("{}\n{}\n".format(countdown_text, seconds_elapsed))
                stdscr.erase()
                try:
                    draw_text(
                        stdscr,
                        countdown_text if no_figlet else figlet.renderText(countdown_text),
                        fallback=countdown_text,
                        title=title,
                    )
                except CharNotPrinted:
                    draw_text(stdscr, "E")
            sleep_target = sync_start + timedelta(seconds=seconds_elapsed + 1)
            if time:
                sleep_target = sleep_target.replace(microsecond=0)
            now = datetime.now()
            if sleep_target > now:
                try:
                    input_action = input_queue.get(True, (sleep_target - now).total_seconds())
                except Empty:
                    input_action = None
                if input_action == INPUT_PAUSE:
                    pause_start = datetime.now()
                    with curses_lock:
                        if not no_window_title:
                            os.write(stdout.fileno(), "\033]2;{0}\007".format(countdown_text).encode())
                        if outfile:
                            with open(outfile, 'w') as f:
                                f.write("{}\n{}\n".format(countdown_text, seconds_elapsed))
                        stdscr.erase()
                        try:
                            draw_text(
                                stdscr,
                                countdown_text if no_figlet else figlet.renderText(countdown_text),
                                color=3,
                                fallback=countdown_text,
                                title=title,
                            )
                        except CharNotPrinted:
                            draw_text(stdscr, "E")
                    input_action = input_queue.get()
                    if input_action == INPUT_PAUSE:
                        sync_start += (datetime.now() - pause_start)
                        pause_start = None
                if input_action == INPUT_EXIT:  # no elif here! input_action may have changed
                    if pause_start:
                        sync_start += (datetime.now() - pause_start)
                        pause_start = None
                    break
                elif input_action == INPUT_RESET:
                    sync_start = datetime.now()
                    laps = []
                    seconds_elapsed = 0
                elif input_action == INPUT_LAP:
                    if pause_start:
                        sync_start += (datetime.now() - pause_start)
                        pause_start = None
                    laps.append((datetime.now() - sync_start).total_seconds())
                    sync_start = datetime.now()
                    seconds_elapsed = 0
            seconds_elapsed = int((datetime.now() - sync_start).total_seconds())
    finally:
        with curses_lock:
            if not no_window_title:
                os.write(stdout.fileno(), "\033]2;\007".encode())
            if outfile:
                os.remove(outfile)
        quit_event.set()
        input_thread.join()
    return (datetime.now() - sync_start).total_seconds(), laps
Ejemplo n.º 42
0
Archivo: wtf.py Proyecto: MareoRaft/wtf
    return g

class StoreTupleAction(argparse.Action):
    def __call__(self, p, ns, values, ostr):
        setattr(ns, self.dest, (self.const, values))

eol_name2val = {'crlf':'\r\n', 'lf':'\n', 'cr':'\r', 'native':os.linesep, 'first':None}
eol_val2name = {'\r\n':'crlf', '\n':'lf', '\r':'cr'}
nullout = open(os.devnull, 'wb')

# make stdin and stdout not do any EOL translations on Windows
if os.name=='nt':
    import msvcrt
    msvcrt.setmode(stdin.fileno(), os.O_BINARY)
    msvcrt.setmode(stdout.fileno(), os.O_BINARY)

def parse_args():
    p = argparse.ArgumentParser(formatter_class=argparse.RawDescriptionHelpFormatter,
        description='''
        Whitespace Total Fixer. Fixes and/or reports all manner of
        annoying issues with whitespace or line endings in text files.

        Exit codes on successful operation:
            0: no issues seen
            10: issues fixed
            20: unfixed issues seen

        http://github.com/dlenski/wtf''')

    g=p.add_argument_group("Input/output modes")
Ejemplo n.º 43
0
def countdown(
    stdscr,
    alt_format=False,
    font=DEFAULT_FONT,
    blink=False,
    critical=3,
    quit_after=None,
    text=None,
    timespec=None,
    title=None,
    voice=None,
    no_seconds=False,
    no_text_magic=True,
    no_figlet=False,
    no_window_title=False,
    **kwargs
):
    try:
        sync_start, target = parse_timestr(timespec)
    except ValueError:
        click.echo("Unable to parse TIME value '{}'".format(timespec))
        exit(64)
    curses_lock, input_queue, quit_event = setup(stdscr)
    figlet = Figlet(font=font)

    if title and not no_figlet:
        title = figlet.renderText(title)

    input_thread = Thread(
        args=(stdscr, input_queue, quit_event, curses_lock),
        target=input_thread_body,
    )
    input_thread.start()

    seconds_total = seconds_left = int(ceil((target - datetime.now()).total_seconds()))

    try:
        while seconds_left > 0 or blink or text:
            figlet.width = stdscr.getmaxyx()[1]
            if alt_format:
                countdown_text = format_seconds_alt(
                    seconds_left, seconds_total, hide_seconds=no_seconds)
            else:
                countdown_text = format_seconds(seconds_left, hide_seconds=no_seconds)
            if seconds_left > 0:
                with curses_lock:
                    if not no_window_title:
                        os.write(stdout.fileno(), "\033]2;{0}\007".format(countdown_text).encode())
                    stdscr.erase()
                    draw_text(
                        stdscr,
                        countdown_text if no_figlet else figlet.renderText(countdown_text),
                        color=1 if seconds_left <= critical else 0,
                        fallback=countdown_text,
                        title=title,
                    )
            if seconds_left <= 10 and voice:
                voice_exec = "echo"
                if os.path.exists("/usr/bin/say"):
                    voice_exec = "/usr/bin/say"
                elif os.path.exists("/usr/bin/espeak"):
                    voice_exec = "/usr/bin/espeak"
                Popen([voice_exec, "-v", voice, str(seconds_left)])

            # We want to sleep until this point of time has been
            # reached:
            sleep_target = sync_start + timedelta(seconds=1)

            # If sync_start has microsecond=0, it might happen that we
            # need to skip one frame (the very first one). This occurs
            # when the program has been startet at, say,
            # "2014-05-29 20:27:57.930651". Now suppose rendering the
            # frame took about 0.2 seconds. The real time now is
            # "2014-05-29 20:27:58.130000" and sleep_target is
            # "2014-05-29 20:27:58.000000" which is in the past! We're
            # already too late. We could either skip that frame
            # completely or we can draw it right now. I chose to do the
            # latter: Only sleep if haven't already missed our target.
            now = datetime.now()
            if sleep_target > now and seconds_left > 0:
                try:
                    input_action = input_queue.get(True, (sleep_target - now).total_seconds())
                except Empty:
                    input_action = None
                if input_action == INPUT_PAUSE:
                    pause_start = datetime.now()
                    with curses_lock:
                        stdscr.erase()
                        draw_text(
                            stdscr,
                            countdown_text if no_figlet else figlet.renderText(countdown_text),
                            color=3,
                            fallback=countdown_text,
                        )
                    input_action = input_queue.get()
                    if input_action == INPUT_PAUSE:
                        sync_start += (datetime.now() - pause_start)
                        target += (datetime.now() - pause_start)
                if input_action == INPUT_EXIT:  # no elif here! input_action may have changed
                    break
                elif input_action == INPUT_RESET:
                    sync_start, target = parse_timestr(timespec)
                    seconds_left = int(ceil((target - datetime.now()).total_seconds()))
                    continue
                elif input_action == INPUT_LAP:
                    continue

            sync_start = sleep_target

            seconds_left = int(ceil((target - datetime.now()).total_seconds()))

            if seconds_left <= 0:
                # we could write this entire block outside the parent while
                # but that would leave us unable to reset everything

                with curses_lock:
                    curses.beep()

                if text and not no_text_magic:
                    text = normalize_text(text)

                rendered_text = text

                if text and not no_figlet:
                    rendered_text = figlet.renderText(text)

                if blink or text:
                    base_color = 1 if blink else 0
                    blink_reset = False
                    flip = True
                    slept = 0
                    extra_sleep = 0
                    while True:
                        with curses_lock:
                            os.write(stdout.fileno(), "\033]2;{0}\007".format("/" if flip else "\\").encode())
                            if text:
                                draw_text(
                                    stdscr,
                                    rendered_text,
                                    color=base_color if flip else 4,
                                    fallback=text,
                                )
                            else:
                                draw_text(stdscr, "", color=base_color if flip else 4)
                        if blink:
                            flip = not flip
                        try:
                            sleep_start = datetime.now()
                            input_action = input_queue.get(True, 0.5 + extra_sleep)
                        except Empty:
                            input_action = None
                        finally:
                            extra_sleep = 0
                            sleep_end = datetime.now()
                        if input_action == INPUT_PAUSE:
                            pause_start = datetime.now()
                            input_action = input_queue.get()
                            extra_sleep = (sleep_end - sleep_start).total_seconds()
                        if input_action == INPUT_EXIT:
                            # no elif here! input_action may have changed
                            return
                        elif input_action == INPUT_RESET:
                            sync_start, target = parse_timestr(timespec)
                            seconds_left = int(ceil((target - datetime.now()).total_seconds()))
                            blink_reset = True
                            break
                        slept += (sleep_end - sleep_start).total_seconds()
                        if quit_after and slept >= float(quit_after):
                            return
                    if blink_reset:
                        continue
    finally:
        with curses_lock:
            if not no_window_title:
                os.write(stdout.fileno(), "\033]2;\007".encode())
        quit_event.set()
        input_thread.join()
Ejemplo n.º 44
0
#!/usr/bin/python

from sys import stdin, stdout, stderr, argv
from os import fdopen

mac_logout_time = 100

mac_hash = {}
sumDb = 0
minDb = 100
nDb = 0
lastSec = "0"

ub_stdout = fdopen(stdout.fileno(), 'w', 0)

ub_mac_logout = open(argv[1], "a", 0)

for line in stdin:
    fields = line.rstrip().split()
    time = fields[0]
    sec = time.split(".",1)[0]

    macTA = ""
    db = 100
    for f in fields:
        if f.startswith("-") and f.endswith("dB"):
            db = int(f.split("-",1)[1].split("d",1)[0])
        if f.startswith("TA:") or f.startswith("SA:"):
            macTA = f.split(":",1)[1]

    if int(sec) - int(lastSec) >= mac_logout_time:
Ejemplo n.º 45
0
# daemonize
if not options.foreground:
    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())

# our list of codes
codes = []

script_path = path.abspath(path.dirname(__file__))

# open codes file
try:
    f = open(script_path + "/rfid_codes.txt", "r")
    for line in f:
        codes.append(line.split("#")[0].strip())
    f.close()
except:
    print ("Could Find Code File")
Ejemplo n.º 46
0
def countdown(stdscr,
              alt_format=False,
              font=DEFAULT_FONT,
              blink=False,
              critical=3,
              quit_after=None,
              text=None,
              timespec=None,
              title=None,
              voice=None,
              voice_prefix=None,
              exec_cmd=None,
              outfile=None,
              no_bell=False,
              no_seconds=False,
              no_text_magic=True,
              no_figlet=False,
              no_figlet_y_offset=-1,
              no_window_title=False,
              time=False,
              time_format=None,
              **kwargs):
    try:
        sync_start, target = parse_timestr(timespec)
    except ValueError:
        raise click.BadParameter(
            "Unable to parse TIME value '{}'".format(timespec))
    curses_lock, input_queue, quit_event = setup(stdscr)
    figlet = Figlet(font=font)
    if not no_figlet:
        no_figlet_y_offset = -1

    if title and not no_figlet:
        try:
            title = figlet.renderText(title)
        except CharNotPrinted:
            title = ""

    voice_cmd = None
    if voice:
        for cmd in ("/usr/bin/say", "/usr/bin/espeak"):
            if os.path.exists(cmd):
                voice_cmd = cmd
                break
    if voice or exec_cmd:
        voice_prefix = voice_prefix or ""

    input_thread = Thread(
        args=(stdscr, input_queue, quit_event, curses_lock),
        target=input_thread_body,
    )
    input_thread.start()

    seconds_total = seconds_left = int(
        ceil((target - datetime.now()).total_seconds()))

    try:
        while seconds_left > 0 or blink or text:
            figlet.width = stdscr.getmaxyx()[1]
            if time:
                countdown_text = datetime.now().strftime(time_format)
            elif alt_format:
                countdown_text = format_seconds_alt(seconds_left,
                                                    seconds_total,
                                                    hide_seconds=no_seconds)
            else:
                countdown_text = format_seconds(seconds_left,
                                                hide_seconds=no_seconds)
            if seconds_left > 0:
                with curses_lock:
                    if not no_window_title:
                        os.write(
                            stdout.fileno(),
                            "\033]2;{0}\007".format(countdown_text).encode())
                    if outfile:
                        with open(outfile, 'w') as f:
                            f.write("{}\n{}\n".format(countdown_text,
                                                      seconds_left))
                    stdscr.erase()
                    try:
                        draw_text(
                            stdscr,
                            countdown_text if no_figlet else
                            figlet.renderText(countdown_text),
                            color=1 if seconds_left <= critical else 0,
                            fallback=title + "\n" +
                            countdown_text if title else countdown_text,
                            title=title,
                            no_figlet_y_offset=no_figlet_y_offset,
                        )
                    except CharNotPrinted:
                        draw_text(stdscr, "E")
            annunciation = None
            if seconds_left <= critical:
                annunciation = str(seconds_left)
            elif seconds_left in (5, 10, 20, 30, 60):
                annunciation = "{} {} seconds".format(voice_prefix,
                                                      seconds_left)
            elif seconds_left in (300, 600, 1800):
                annunciation = "{} {} minutes".format(voice_prefix,
                                                      int(seconds_left / 60))
            elif seconds_left == 3600:
                annunciation = "{} one hour".format(voice_prefix)
            if annunciation or exec_cmd:
                if exec_cmd:
                    Popen(
                        exec_cmd.format(seconds_left, annunciation or ""),
                        stdout=DEVNULL,
                        stderr=STDOUT,
                        shell=True,
                    )

                if voice_cmd:
                    Popen(
                        [voice_cmd, "-v", voice,
                         annunciation.strip()],
                        stdout=DEVNULL,
                        stderr=STDOUT,
                    )

            # We want to sleep until this point of time has been
            # reached:
            sleep_target = sync_start + timedelta(seconds=1)
            if time:
                sleep_target = sleep_target.replace(microsecond=0)

            # If sync_start has microsecond=0, it might happen that we
            # need to skip one frame (the very first one). This occurs
            # when the program has been startet at, say,
            # "2014-05-29 20:27:57.930651". Now suppose rendering the
            # frame took about 0.2 seconds. The real time now is
            # "2014-05-29 20:27:58.130000" and sleep_target is
            # "2014-05-29 20:27:58.000000" which is in the past! We're
            # already too late. We could either skip that frame
            # completely or we can draw it right now. I chose to do the
            # latter: Only sleep if haven't already missed our target.
            now = datetime.now()
            if sleep_target > now and seconds_left > 0:
                try:
                    input_action = input_queue.get(True, (sleep_target -
                                                          now).total_seconds())
                except Empty:
                    input_action = None
                if input_action == INPUT_PAUSE:
                    pause_start = datetime.now()
                    with curses_lock:
                        stdscr.erase()
                        try:
                            draw_text(
                                stdscr,
                                countdown_text if no_figlet else
                                figlet.renderText(countdown_text),
                                color=3,
                                fallback=countdown_text,
                                title=title,
                                no_figlet_y_offset=no_figlet_y_offset,
                            )
                        except CharNotPrinted:
                            draw_text(stdscr, "E")
                    input_action = input_queue.get()
                    if input_action == INPUT_PAUSE:
                        time_paused = datetime.now() - pause_start
                        sync_start += time_paused
                        target += time_paused
                if input_action == INPUT_EXIT:  # no elif here! input_action may have changed
                    break
                elif input_action == INPUT_RESET:
                    sync_start, target = parse_timestr(timespec)
                    seconds_left = int(
                        ceil((target - datetime.now()).total_seconds()))
                    continue
                elif input_action == INPUT_PLUS:
                    target += timedelta(seconds=10)
                elif input_action == INPUT_MINUS:
                    target -= timedelta(seconds=10)
                elif input_action == INPUT_LAP:
                    continue

            sync_start = sleep_target

            seconds_left = int(ceil((target - datetime.now()).total_seconds()))

            if seconds_left <= 0:
                # we could write this entire block outside the parent while
                # but that would leave us unable to reset everything

                if not no_bell:
                    with curses_lock:
                        curses.beep()

                if text and not no_text_magic:
                    text = normalize_text(text)

                if outfile:
                    with open(outfile, 'w') as f:
                        f.write("{}\n{}\n".format(text if text else "DONE", 0))

                rendered_text = text

                if text and not no_figlet:
                    try:
                        rendered_text = figlet.renderText(text)
                    except CharNotPrinted:
                        rendered_text = ""

                if blink or text:
                    base_color = 1 if blink else 0
                    blink_reset = False
                    flip = True
                    slept = 0
                    extra_sleep = 0
                    while True:
                        with curses_lock:
                            os.write(
                                stdout.fileno(), "\033]2;{0}\007".format(
                                    "/" if flip else "\\").encode())
                            if text:
                                draw_text(
                                    stdscr,
                                    rendered_text,
                                    color=base_color if flip else 4,
                                    fallback=text,
                                    no_figlet_y_offset=no_figlet_y_offset,
                                )
                            else:
                                draw_text(stdscr,
                                          "",
                                          color=base_color if flip else 4)
                        if blink:
                            flip = not flip
                        try:
                            sleep_start = datetime.now()
                            input_action = input_queue.get(
                                True, 0.5 + extra_sleep)
                        except Empty:
                            input_action = None
                        finally:
                            extra_sleep = 0
                            sleep_end = datetime.now()
                        if input_action == INPUT_PAUSE:
                            pause_start = datetime.now()
                            input_action = input_queue.get()
                            extra_sleep = (sleep_end -
                                           sleep_start).total_seconds()
                        if input_action == INPUT_EXIT:
                            # no elif here! input_action may have changed
                            return
                        elif input_action == INPUT_RESET:
                            sync_start, target = parse_timestr(timespec)
                            seconds_left = int(
                                ceil(
                                    (target - datetime.now()).total_seconds()))
                            blink_reset = True
                            break
                        slept += (sleep_end - sleep_start).total_seconds()
                        if quit_after and slept >= float(quit_after):
                            return
                    if blink_reset:
                        continue
    finally:
        with curses_lock:
            if not no_window_title:
                os.write(stdout.fileno(), "\033]2;\007".encode())
            if outfile:
                os.remove(outfile)
        quit_event.set()
        input_thread.join()
Ejemplo n.º 47
0
def retvalue(command, valt='turn-on', valf='turn-off'):
    child = sp.Popen(command, stdout=sp.PIPE, stderr=stdout.fileno(), shell=True)
    retcode = child.communicate()[0]
    return int(child.returncode)
Ejemplo n.º 48
0
#!/usr/bin/env python

from __future__ import print_function
from datetime import datetime
from struct import pack
from time import sleep
from sys import stdout, stderr
import os

sleep_time = int(os.environ.get('SLEEP_TIME', 10))

# Turn off stdout buffering
stdout = os.fdopen(stdout.fileno(), 'w', 0)

print('clock controller: syncing every %d seconds' % sleep_time, file=stderr)

while True:
    now = datetime.now()

    # convert to 12-hour
    hour = 12 if ((now.hour % 12) == 0) else (now.hour % 12)
    minute, second, pm = now.minute, now.second, (now.hour > 11)

    time_msg = ('[', pack('>BBBB', hour, minute, second, pm), '%]')
    print(*time_msg, sep='', file=stdout)

    sleep(sleep_time)

Ejemplo n.º 49
0
def darwin_iterm2_shell_is_focused():
    focused_tty = osascript_tell(
        'iTerm',
        'tty of current session of current terminal',
    )
    return focused_tty == ttyname(stdout.fileno())
Ejemplo n.º 50
0
    def __init__(self,
                 libmadx=None,
                 command_log=None,
                 stdout=None,
                 history=None,
                 **Popen_args):
        """
        Initialize instance variables.

        :param libmadx: :mod:`libmadx` compatible object
        :param command_log: Log all MAD-X commands issued via cpymad.
        :param stdout: file descriptor, file object or callable
        :param Popen_args: Additional parameters to ``subprocess.Popen``

        If ``libmadx`` is NOT specified, a new MAD-X interpreter will
        automatically be spawned. This is what you will mostly want to do. In
        this case any additional keyword arguments are forwarded to
        ``subprocess.Popen``. The most prominent use case for this is to
        redirect or suppress the MAD-X standard I/O::

            m = Madx(stdout=False)

            with open('madx_output.log', 'w') as f:
                m = Madx(stdout=f)

            m = Madx(stdout=sys.stdout)
        """
        # open history file
        if isinstance(command_log, basestring):
            command_log = CommandLog.create(command_log)
        self.reader = NullContext()
        # start libmadx subprocess
        if libmadx is None:
            if stdout is None:
                from sys import stdout
            if hasattr(stdout, 'write'):
                try:
                    stdout = stdout.fileno()
                except (AttributeError, OSError, IOError):
                    stdout = stdout.write
            Popen_args['stdout'] = \
                subprocess.PIPE if callable(stdout) else stdout
            # stdin=None leads to an error on windows when STDIN is broken.
            # Therefore, we need set stdin=os.devnull by passing stdin=False:
            Popen_args.setdefault('stdin', False)
            Popen_args.setdefault('bufsize', 0)
            self._service, self._process = \
                _rpc.LibMadxClient.spawn_subprocess(**Popen_args)
            libmadx = self._service.libmadx
            if callable(stdout):
                self.reader = AsyncReader(self._process.stdout, stdout)
        if not libmadx.is_started():
            with self.reader:
                libmadx.start()
        # init instance variables:
        self.history = history
        self._libmadx = libmadx
        self._command_log = command_log
        self.command = CommandMap(self)
        self.globals = VarList(self)
        self.elements = GlobalElementList(self)
        self.base_types = BaseTypeMap(self)
        self.sequence = SequenceMap(self)
        self.table = TableMap(self._libmadx)
        self._enter_count = 0
        self._batch = None
Ejemplo n.º 51
0
def _terminalSize():
    fd = stdout.fileno()
    size = ioctl(fd, TIOCGWINSZ, '1234')
    height, width = unpack('hh', size)
    return (width, height)
Ejemplo n.º 52
0
#!/usr/bin/python
from getopt import getopt
from itertools import count
from logging import getLogger, Formatter, FileHandler, StreamHandler, DEBUG, INFO, WARNING
from re import match
from os import fdopen, listdir, makedirs, remove
from os.path import getmtime, getsize, isdir, isfile, join, lexists
from subprocess import Popen, PIPE, STDOUT
from sys import argv, exit, getfilesystemencoding, platform, stdout  # pylint: disable=W0622
from time import sleep, time
from traceback import format_exc

# Console output encoding and buffering problems fixing
stdout = fdopen(stdout.fileno(), "w", 0)

# ToDo: Report non-mentioned videos
# ToDo: Verify already downloaded videos
# ToDo: Do something to Knudepunkt TV problem
# ToDo: Check video author, report it and do not attempt settings
# ToDo: Gather all errors to re-display in the end

try:  # Selenium configuration
    import selenium

    if tuple(int(v) for v in selenium.__version__.split(".")) < (2, 45):
        raise ImportError("Selenium version %s < 2.45" % selenium.__version__)
    from selenium import webdriver
    from selenium.common.exceptions import NoSuchElementException

    DRIVERS = dict(
        (v.lower(), (v, getattr(webdriver, v))) for v in vars(webdriver) if v[0].isupper()
Ejemplo n.º 53
0
def unix_startup(config, user=None, debug=False):
    """ Unix specific startup actions """
    global pidfile
    if user:
        try:
            userpw = getpwnam(user)
            setegid(userpw[3])
            seteuid(userpw[2])
        except:
            t, val, tb = exc_info()
            del t, tb
            print "Cannot swith to user", user, str(val)
            sys_exit(-2)
    else:
        user = getpwuid(getuid())[0]

    try:
        pidfile = config.get("global", "pidfile")
    except:
        LOG(E_ALWAYS, "[Main] Missing pidfile in config")
        do_shutdown(-4)

    locked = 1
    try:
        pid = int(open(pidfile).read().strip())
        LOG(E_TRACE, "[Main] Lock: Sending signal to the process")
        try:
            kill(pid, 0)
            LOG(E_ERR, "[Main] Stale Lockfile: Process is alive")
        except:
            LOG(E_ERR, "[Main] Stale Lockfile: Old process is not alive")
            locked = 0
    except:
        locked = 0

    if locked:
        LOG(E_ALWAYS, "[Main] Unable to start Netfarm Archiver, another instance is running")
        do_shutdown(-5)

    ## Daemonize - Unix only - win32 has service
    if not debug:
        try:
            pid = fork()
        except:
            t, val, tb = exc_info()
            del t
            print "Cannot go in background mode", str(val)

        if pid:
            sys_exit(0)

        chdir("/")
        null = open("/dev/null", "r")
        close(stdin.fileno())
        dup(null.fileno())
        null.close()
        close(stdout.fileno())
        dup(LOG.fileno())
        close(stderr.fileno())
        dup(LOG.fileno())

    ## Save my process id to file
    mypid = str(getpid())
    try:
        open(pidfile, "w").write(mypid)
    except:
        LOG(E_ALWAYS, "[Main] Pidfile is not writable")
        do_shutdown(-6)

    return user, mypid
Ejemplo n.º 54
0
def countdown(
    stdscr,
    alt_format=False,
    font=DEFAULT_FONT,
    blink=False,
    critical=3,
    quit_after=None,
    text=None,
    timespec=None,
    title=None,
    voice=None,
    voice_prefix=None,
    outfile=None,
    no_bell=False,
    no_seconds=False,
    no_text_magic=True,
    no_figlet=False,
    no_window_title=False,
    time=False,
    time_format=None,
    **kwargs
):
    try:
        sync_start, target = parse_timestr(timespec)
    except ValueError:
        raise click.BadParameter("Unable to parse TIME value '{}'".format(timespec))
    curses_lock, input_queue, quit_event = setup(stdscr)
    figlet = Figlet(font=font)

    if title and not no_figlet:
        try:
            title = figlet.renderText(title)
        except CharNotPrinted:
            title = ""

    voice_cmd = None
    if voice:
        for cmd in ("/usr/bin/say", "/usr/bin/espeak"):
            if os.path.exists(cmd):
                voice_cmd = cmd
                break
        voice_prefix = voice_prefix or ""

    input_thread = Thread(
        args=(stdscr, input_queue, quit_event, curses_lock),
        target=input_thread_body,
    )
    input_thread.start()

    seconds_total = seconds_left = int(ceil((target - datetime.now()).total_seconds()))

    try:
        while seconds_left > 0 or blink or text:
            figlet.width = stdscr.getmaxyx()[1]
            if time:
                countdown_text = datetime.now().strftime(time_format)
            elif alt_format:
                countdown_text = format_seconds_alt(
                    seconds_left, seconds_total, hide_seconds=no_seconds)
            else:
                countdown_text = format_seconds(seconds_left, hide_seconds=no_seconds)
            if seconds_left > 0:
                with curses_lock:
                    if not no_window_title:
                        os.write(stdout.fileno(), "\033]2;{0}\007".format(countdown_text).encode())
                    if outfile:
                        with open(outfile, 'w') as f:
                            f.write("{}\n{}\n".format(countdown_text, seconds_left))
                    stdscr.erase()
                    try:
                        draw_text(
                            stdscr,
                            countdown_text if no_figlet else figlet.renderText(countdown_text),
                            color=1 if seconds_left <= critical else 0,
                            fallback=title + "\n" + countdown_text if title else countdown_text,
                            title=title,
                        )
                    except CharNotPrinted:
                        draw_text(stdscr, "E")
            if voice_cmd:
                announciation = None
                if seconds_left <= critical:
                    announciation = str(seconds_left)
                elif seconds_left in (5, 10, 20, 30, 60):
                    announciation = "{} {} seconds".format(voice_prefix, seconds_left)
                elif seconds_left in (300, 600, 1800):
                    announciation = "{} {} minutes".format(voice_prefix, int(seconds_left / 60))
                elif seconds_left == 3600:
                    announciation = "{} one hour".format(voice_prefix)
                if announciation:
                    Popen(
                        [voice_cmd, "-v", voice, announciation.strip()],
                        stdout=DEVNULL,
                        stderr=STDOUT,
                    )

            # We want to sleep until this point of time has been
            # reached:
            sleep_target = sync_start + timedelta(seconds=1)
            if time:
                sleep_target = sleep_target.replace(microsecond=0)

            # If sync_start has microsecond=0, it might happen that we
            # need to skip one frame (the very first one). This occurs
            # when the program has been startet at, say,
            # "2014-05-29 20:27:57.930651". Now suppose rendering the
            # frame took about 0.2 seconds. The real time now is
            # "2014-05-29 20:27:58.130000" and sleep_target is
            # "2014-05-29 20:27:58.000000" which is in the past! We're
            # already too late. We could either skip that frame
            # completely or we can draw it right now. I chose to do the
            # latter: Only sleep if haven't already missed our target.
            now = datetime.now()
            if sleep_target > now and seconds_left > 0:
                try:
                    input_action = input_queue.get(True, (sleep_target - now).total_seconds())
                except Empty:
                    input_action = None
                if input_action == INPUT_PAUSE:
                    pause_start = datetime.now()
                    with curses_lock:
                        stdscr.erase()
                        try:
                            draw_text(
                                stdscr,
                                countdown_text if no_figlet else figlet.renderText(countdown_text),
                                color=3,
                                fallback=countdown_text,
                            )
                        except CharNotPrinted:
                            draw_text(stdscr, "E")
                    input_action = input_queue.get()
                    if input_action == INPUT_PAUSE:
                        time_paused = datetime.now() - pause_start
                        sync_start += time_paused
                        target += time_paused
                if input_action == INPUT_EXIT:  # no elif here! input_action may have changed
                    break
                elif input_action == INPUT_RESET:
                    sync_start, target = parse_timestr(timespec)
                    seconds_left = int(ceil((target - datetime.now()).total_seconds()))
                    continue
                elif input_action == INPUT_LAP:
                    continue

            sync_start = sleep_target

            seconds_left = int(ceil((target - datetime.now()).total_seconds()))

            if seconds_left <= 0:
                # we could write this entire block outside the parent while
                # but that would leave us unable to reset everything

                if not no_bell:
                    with curses_lock:
                        curses.beep()

                if text and not no_text_magic:
                    text = normalize_text(text)

                if outfile:
                    with open(outfile, 'w') as f:
                        f.write("{}\n{}\n".format(text if text else "DONE", 0))

                rendered_text = text

                if text and not no_figlet:
                    try:
                        rendered_text = figlet.renderText(text)
                    except CharNotPrinted:
                        rendered_text = ""

                if blink or text:
                    base_color = 1 if blink else 0
                    blink_reset = False
                    flip = True
                    slept = 0
                    extra_sleep = 0
                    while True:
                        with curses_lock:
                            os.write(stdout.fileno(), "\033]2;{0}\007".format("/" if flip else "\\").encode())
                            if text:
                                draw_text(
                                    stdscr,
                                    rendered_text,
                                    color=base_color if flip else 4,
                                    fallback=text,
                                )
                            else:
                                draw_text(stdscr, "", color=base_color if flip else 4)
                        if blink:
                            flip = not flip
                        try:
                            sleep_start = datetime.now()
                            input_action = input_queue.get(True, 0.5 + extra_sleep)
                        except Empty:
                            input_action = None
                        finally:
                            extra_sleep = 0
                            sleep_end = datetime.now()
                        if input_action == INPUT_PAUSE:
                            pause_start = datetime.now()
                            input_action = input_queue.get()
                            extra_sleep = (sleep_end - sleep_start).total_seconds()
                        if input_action == INPUT_EXIT:
                            # no elif here! input_action may have changed
                            return
                        elif input_action == INPUT_RESET:
                            sync_start, target = parse_timestr(timespec)
                            seconds_left = int(ceil((target - datetime.now()).total_seconds()))
                            blink_reset = True
                            break
                        slept += (sleep_end - sleep_start).total_seconds()
                        if quit_after and slept >= float(quit_after):
                            return
                    if blink_reset:
                        continue
    finally:
        with curses_lock:
            if not no_window_title:
                os.write(stdout.fileno(), "\033]2;\007".encode())
            if outfile:
                os.remove(outfile)
        quit_event.set()
        input_thread.join()
Ejemplo n.º 55
0
def stopwatch(stdscr,
              alt_format=False,
              critical=3,
              exec_cmd=None,
              font=DEFAULT_FONT,
              no_figlet=False,
              no_figlet_y_offset=-1,
              no_seconds=False,
              quit_after=None,
              title=None,
              outfile=None,
              no_window_title=False,
              time=False,
              time_format=None,
              voice_prefix=None,
              **kwargs):
    curses_lock, input_queue, quit_event = setup(stdscr)
    figlet = Figlet(font=font)

    if not no_figlet:
        no_figlet_y_offset = -1
    if title and not no_figlet:
        try:
            title = figlet.renderText(title)
        except CharNotPrinted:
            title = ""

    input_thread = Thread(
        args=(stdscr, input_queue, quit_event, curses_lock),
        target=input_thread_body,
    )
    input_thread.start()

    try:
        sync_start = datetime.now()
        pause_start = None
        seconds_elapsed = 0
        laps = []
        while quit_after is None or seconds_elapsed < int(quit_after):
            figlet.width = stdscr.getmaxyx()[1]
            if time:
                stopwatch_text = datetime.now().strftime(time_format)
            elif alt_format:
                stopwatch_text = format_seconds_alt(seconds_elapsed,
                                                    0,
                                                    hide_seconds=no_seconds)
            else:
                stopwatch_text = format_seconds(seconds_elapsed,
                                                hide_seconds=no_seconds)
            with curses_lock:
                if not no_window_title:
                    os.write(stdout.fileno(),
                             "\033]2;{0}\007".format(stopwatch_text).encode())
                if outfile:
                    with open(outfile, 'w') as f:
                        f.write("{}\n{}\n".format(stopwatch_text,
                                                  seconds_elapsed))
                stdscr.erase()
                try:
                    draw_text(
                        stdscr,
                        stopwatch_text
                        if no_figlet else figlet.renderText(stopwatch_text),
                        fallback=stopwatch_text,
                        title=title,
                        no_figlet_y_offset=no_figlet_y_offset,
                    )
                except CharNotPrinted:
                    draw_text(stdscr, "E")
            if exec_cmd:
                voice_prefix = voice_prefix or ""
                annunciation = ""
                if seconds_elapsed <= critical and seconds_elapsed > 0:
                    annunciation = str(seconds_elapsed)
                elif seconds_elapsed in (5, 10, 20, 30, 40, 50, 60):
                    annunciation = "{} {} seconds".format(
                        voice_prefix, seconds_elapsed)
                elif seconds_elapsed in (120, 180, 300, 600, 1800):
                    annunciation = "{} {} minutes".format(
                        voice_prefix, int(seconds_elapsed / 60))
                elif seconds_elapsed == 3600:
                    annunciation = "{} one hour".format(voice_prefix)
                elif seconds_elapsed % 3600 == 0 and seconds_elapsed > 0:
                    annunciation = "{} {} hours".format(
                        voice_prefix, int(seconds_elapsed / 3600))
                Popen(
                    exec_cmd.format(seconds_elapsed, annunciation),
                    stdout=DEVNULL,
                    stderr=STDOUT,
                    shell=True,
                )
            sleep_target = sync_start + timedelta(seconds=seconds_elapsed + 1)
            if time:
                sleep_target = sleep_target.replace(microsecond=0)
            now = datetime.now()
            if sleep_target > now:
                try:
                    input_action = input_queue.get(True, (sleep_target -
                                                          now).total_seconds())
                except Empty:
                    input_action = None
                if input_action == INPUT_PAUSE:
                    pause_start = datetime.now()
                    with curses_lock:
                        if not no_window_title:
                            os.write(
                                stdout.fileno(), "\033]2;{0}\007".format(
                                    stopwatch_text).encode())
                        if outfile:
                            with open(outfile, 'w') as f:
                                f.write("{}\n{}\n".format(
                                    stopwatch_text, seconds_elapsed))
                        stdscr.erase()
                        try:
                            draw_text(
                                stdscr,
                                stopwatch_text if no_figlet else
                                figlet.renderText(stopwatch_text),
                                color=3,
                                fallback=stopwatch_text,
                                title=title,
                                no_figlet_y_offset=no_figlet_y_offset,
                            )
                        except CharNotPrinted:
                            draw_text(stdscr, "E")
                    input_action = input_queue.get()
                    if input_action == INPUT_PAUSE:
                        sync_start += (datetime.now() - pause_start)
                        pause_start = None
                if input_action == INPUT_EXIT:  # no elif here! input_action may have changed
                    if pause_start:
                        sync_start += (datetime.now() - pause_start)
                        pause_start = None
                    break
                elif input_action == INPUT_RESET:
                    sync_start = datetime.now()
                    laps = []
                    seconds_elapsed = 0
                elif input_action == INPUT_PLUS:
                    sync_start -= timedelta(seconds=10)
                elif input_action == INPUT_MINUS:
                    sync_start += timedelta(seconds=10)
                elif input_action == INPUT_LAP:
                    if pause_start:
                        sync_start += (datetime.now() - pause_start)
                        pause_start = None
                    laps.append((datetime.now() - sync_start).total_seconds())
                    sync_start = datetime.now()
                    seconds_elapsed = 0
            seconds_elapsed = int(
                (datetime.now() - sync_start).total_seconds())
    finally:
        with curses_lock:
            if not no_window_title:
                os.write(stdout.fileno(), "\033]2;\007".encode())
            if outfile:
                os.remove(outfile)
        quit_event.set()
        input_thread.join()
    return (datetime.now() - sync_start).total_seconds(), laps
Ejemplo n.º 56
0
def darwin_iterm2_shell_is_focused():
    focused_tty = osascript_tell(
        'iTerm',
        'tty of current session of current terminal',
    )
    return focused_tty == ttyname(stdout.fileno())
Ejemplo n.º 57
0
from sys import stderr, stdout, exit
import os
import traceback
from collections import defaultdict

from PyPDF2 import PdfFileMerger, parse_filename_page_ranges


if __name__ == "__main__":
    args = parse_args()
    filename_page_ranges = parse_filename_page_ranges(args.fn_pgrgs)
    if args.output:
        output = open(args.output, "wb")
    else:
        stdout.flush()
        output = os.fdopen(stdout.fileno(), "wb")

    merger = PdfFileMerger()
    in_fs = dict()
    try:
        for (filename, page_range) in filename_page_ranges:
            if args.verbose:
                print(filename, page_range, file=stderr)
            if filename not in in_fs:
                in_fs[filename] = open(filename, "rb")
            merger.append(in_fs[filename], pages=page_range)
    except:
        print(traceback.format_exc(), file=stderr)
        print("Error while reading " + filename, file=stderr)
        exit(1)
    merger.write(output)