Python os.isatty() Examples

The following are 30 code examples of os.isatty(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module os , or try the search function .
Example #1
Source File: ptyprocess.py    From pipenv with MIT License 6 votes vote down vote up
def getecho(self):
        '''This returns the terminal echo mode. This returns True if echo is
        on or False if echo is off. Child applications that are expecting you
        to enter a password often set ECHO False. See waitnoecho().

        Not supported on platforms where ``isatty()`` returns False.  '''

        try:
            attr = termios.tcgetattr(self.fd)
        except termios.error as err:
            errmsg = 'getecho() may not be called on this platform'
            if err.args[0] == errno.EINVAL:
                raise IOError(err.args[0], '%s: %s.' % (err.args[1], errmsg))
            raise

        self.echo = bool(attr[3] & termios.ECHO)
        return self.echo 
Example #2
Source File: plugins.py    From cherrypy with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def _is_daemonized(self):
        """Return boolean indicating if the current process is
        running as a daemon.

        The criteria to determine the `daemon` condition is to verify
        if the current pid is not the same as the one that got used on
        the initial construction of the plugin *and* the stdin is not
        connected to a terminal.

        The sole validation of the tty is not enough when the plugin
        is executing inside other process like in a CI tool
        (Buildbot, Jenkins).
        """
        return (
            self._original_pid != os.getpid() and
            not os.isatty(sys.stdin.fileno())
        ) 
Example #3
Source File: tty.py    From deepWordBug with Apache License 2.0 6 votes vote down vote up
def size(fd):
    """
    Return a tuple (rows,cols) representing the size of the TTY `fd`.

    The provided file descriptor should be the stdout stream of the TTY.

    If the TTY size cannot be determined, returns None.
    """

    if not os.isatty(fd.fileno()):
        return None

    try:
        dims = struct.unpack('hh', fcntl.ioctl(fd, termios.TIOCGWINSZ, 'hhhh'))
    except:
        try:
            dims = (os.environ['LINES'], os.environ['COLUMNS'])
        except:
            return None

    return dims 
Example #4
Source File: fastdupes.py    From fastdupes with GNU General Public License v2.0 6 votes vote down vote up
def write(self, text, newline=False):
        """Use ``\\r`` to overdraw the current line with the given text.

        This function transparently handles tracking how much overdrawing is
        necessary to erase the previous line when used consistently.

        :param text: The text to be outputted
        :param newline: Whether to start a new line and reset the length count.
        :type text: :class:`~__builtins__.str`
        :type newline: :class:`~__builtins__.bool`
        """
        if not self.isatty:
            self.fobj.write('%s\n' % text)
            return

        msg_len = len(text)
        self.max_len = max(self.max_len, msg_len)

        self.fobj.write("\r%-*s" % (self.max_len, text))
        if newline or not self.isatty:
            self.fobj.write('\n')
            self.max_len = 0 
Example #5
Source File: ptyprocess.py    From sublime_debugger with MIT License 6 votes vote down vote up
def getecho(self):
        '''This returns the terminal echo mode. This returns True if echo is
        on or False if echo is off. Child applications that are expecting you
        to enter a password often set ECHO False. See waitnoecho().

        Not supported on platforms where ``isatty()`` returns False.  '''

        try:
            attr = termios.tcgetattr(self.fd)
        except termios.error as err:
            errmsg = 'getecho() may not be called on this platform'
            if err.args[0] == errno.EINVAL:
                raise IOError(err.args[0], '%s: %s.' % (err.args[1], errmsg))
            raise

        self.echo = bool(attr[3] & termios.ECHO)
        return self.echo 
Example #6
Source File: cred.py    From magpy with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def getuser():
    sysuser = os.getenv("USER")
    # if sysuser could not be identified try Logname
    if sysuser == None:
        print("Getuser: Running from crontab -- trying Logname to identify user")
        try:
            sysuser = os.getenv("LOGNAME").replace("LOGNAME=", "")
        except:
            sysuser = None
        if not sysuser == None:
            print("Getuser: ... succes - using", sysuser)
    # if sysuser still could not be identified assume that uid 1000 is the defaultuser (on linux)
    if sysuser == None or sysuser == 'None':
        print("Getuser: Cannot identify user by standard procedures - switching to default uid 1000")
        sysuser = pwd.getpwuid(1000)[0]
        print("Getuser: now using", sysuser)
    return sysuser
    # path to home directory
    #if os.isatty(sys.stdin.fileno()):
    #    sysuser = os.getenv("USER")
    #    pass
    #else:
    #    sysuser = os.getenv("LOGNAME").replace("LOGNAME=", "")
    #    pass 
Example #7
Source File: term.py    From edgedb with Apache License 2.0 6 votes vote down vote up
def size(fileno):
    """Current terminal height and width (lines and columns).

    :params int fileno: file-descriptor
    :returns: Tuple of two integers - lines and columns respectively.
              ``(None, None)`` if ``fileno`` is not a terminal
    """
    if not isatty(fileno):
        return None, None

    try:
        size = struct.unpack(
            '2h', fcntl.ioctl(fileno, termios.TIOCGWINSZ, '    '))
    except Exception:
        size = (os.getenv('LINES', 25), os.getenv('COLUMNS', 80))

    return size 
Example #8
Source File: ipinfo.py    From ivre with GNU General Public License v3.0 6 votes vote down vote up
def disp_recs_json(flt, sort, limit, skip):
    if os.isatty(sys.stdout.fileno()):
        indent = 4
    else:
        indent = None
    for rec in db.passive.get(flt, sort=sort, limit=limit, skip=skip):
        for fld in ['_id', 'scanid']:
            try:
                del rec[fld]
            except KeyError:
                pass
        if (
                rec.get('recontype') == 'SSL_SERVER' and
                rec.get('source') in {'cert', 'cacert'}
        ):
            rec['value'] = utils.encode_b64(rec['value']).decode()
        print(json.dumps(rec, indent=indent, default=db.passive.serialize)) 
Example #9
Source File: ptyprocess.py    From sublime_debugger with MIT License 5 votes vote down vote up
def isatty(self):
        '''This returns True if the file descriptor is open and connected to a
        tty(-like) device, else False.

        On SVR4-style platforms implementing streams, such as SunOS and HP-UX,
        the child pty may not appear as a terminal device.  This means
        methods such as setecho(), setwinsize(), getwinsize() may raise an
        IOError. '''

        return os.isatty(self.fd) 
Example #10
Source File: __init__.py    From camr with GNU General Public License v2.0 5 votes vote down vote up
def isatty(self):
        '''This returns True if the file descriptor is open and connected to a
        tty(-like) device, else False.

        On SVR4-style platforms implementing streams, such as SunOS and HP-UX,
        the child pty may not appear as a terminal device.  This means
        methods such as setecho(), setwinsize(), getwinsize() may raise an
        IOError. '''

        return os.isatty(self.child_fd) 
Example #11
Source File: ptyprocess.py    From sublime_debugger with MIT License 5 votes vote down vote up
def setecho(self, state):
        '''This sets the terminal echo mode on or off. Note that anything the
        child sent before the echo will be lost, so you should be sure that
        your input buffer is empty before you call setecho(). For example, the
        following will work as expected::

            p = pexpect.spawn('cat') # Echo is on by default.
            p.sendline('1234') # We expect see this twice from the child...
            p.expect(['1234']) # ... once from the tty echo...
            p.expect(['1234']) # ... and again from cat itself.
            p.setecho(False) # Turn off tty echo
            p.sendline('abcd') # We will set this only once (echoed by cat).
            p.sendline('wxyz') # We will set this only once (echoed by cat)
            p.expect(['abcd'])
            p.expect(['wxyz'])

        The following WILL NOT WORK because the lines sent before the setecho
        will be lost::

            p = pexpect.spawn('cat')
            p.sendline('1234')
            p.setecho(False) # Turn off tty echo
            p.sendline('abcd') # We will set this only once (echoed by cat).
            p.sendline('wxyz') # We will set this only once (echoed by cat)
            p.expect(['1234'])
            p.expect(['1234'])
            p.expect(['abcd'])
            p.expect(['wxyz'])


        Not supported on platforms where ``isatty()`` returns False.
        '''
        _setecho(self.fd, state)

        self.echo = state 
Example #12
Source File: _pyio.py    From Imogen with MIT License 5 votes vote down vote up
def isatty(self):
        """True if the file is connected to a TTY device."""
        self._checkClosed()
        return os.isatty(self._fd) 
Example #13
Source File: io.py    From django-cloud-deploy with Apache License 2.0 5 votes vote down vote up
def progressbar(self, expect_time: int, message: str):
        """A context manager that shows a progress bar.

        Output of the progress bar will be like the following:
            <message>|██████████∙∙∙∙∙∙∙∙| (ETA:  0:00:05)

        If the task ends earlier than expected, the progress bar will directly
        go to the end.

        Args:
            expect_time: How long the progress bar is going to run.
                (In seconds).
            message: A prefix of the progress bar showing what it is about.

        Yields:
            None
        """

        is_tty = os.isatty(sys.stderr.fileno())
        progress_bar = _ProgressBar(expect_time,
                                    message,
                                    sys.stderr,
                                    tty=is_tty)
        try:
            progress_bar.start()
            yield
        finally:
            progress_bar.finish() 
Example #14
Source File: _pyio.py    From Imogen with MIT License 5 votes vote down vote up
def isatty(self):
        """Return a bool indicating whether this is an 'interactive' stream.

        Return False if it can't be determined.
        """
        self._checkClosed()
        return False

    ### Readline[s] and writelines ### 
Example #15
Source File: _pyio.py    From Imogen with MIT License 5 votes vote down vote up
def isatty(self):
        return self.raw.isatty() 
Example #16
Source File: _pyio.py    From Imogen with MIT License 5 votes vote down vote up
def isatty(self):
        return self.reader.isatty() or self.writer.isatty() 
Example #17
Source File: sh.py    From scylla with Apache License 2.0 5 votes vote down vote up
def ob_is_tty(ob):
    """ checks if an object (like a file-like object) is a tty.  """
    fileno = get_fileno(ob)
    is_tty = False
    if fileno:
        is_tty = os.isatty(fileno)
    return is_tty 
Example #18
Source File: record.py    From Commander with MIT License 5 votes vote down vote up
def display_code(url):
        code, remains, total = get_totp_code(url)
        progress = ''.rjust(remains, '=')
        progress = progress.ljust(total, ' ')
        if os.isatty(0):
            print('\r', end='', flush=True)
            print('\t{0}\t\t[{1}]'.format(code, progress), end='', flush=True)
        else:
            if TotpCommand.LastDisplayedCode != code:
                print('\t{0}\t\tvalid for {1} seconds.'.format(code, remains))
                TotpCommand.LastDisplayedCode = code 
Example #19
Source File: console.py    From click-odoo with GNU Lesser General Public License v3.0 5 votes vote down vote up
def _isatty(stream):
    try:
        return os.isatty(stream.fileno())
    except Exception:
        return False 
Example #20
Source File: pexpect.py    From smod-1 with GNU General Public License v2.0 5 votes vote down vote up
def isatty (self):   # File-like object.

        """This returns True if the file descriptor is open and connected to a
        tty(-like) device, else False. """

        return os.isatty(self.child_fd) 
Example #21
Source File: logutil.py    From votr with Apache License 2.0 5 votes vote down vote up
def wrap_pager():
    if os.isatty(0) and os.isatty(1):
        buf = io.StringIO()
        yield buf
        sp = subprocess.Popen(PAGER, stdin=subprocess.PIPE)
        sp.communicate(buf.getvalue().encode('utf8'))
    else:
        yield sys.stdout


# ---------------------------------------- 
Example #22
Source File: cliutils.py    From pycopia with Apache License 2.0 5 votes vote down vote up
def _get_winsize(fd):
    if os.isatty(fd):
        import fcntl, struct, termios
        WINSIZEFMT = b"HHHH"
        winsize = fcntl.ioctl(fd, termios.TIOCGWINSZ, b"\0"*struct.calcsize(WINSIZEFMT))
        l, c = struct.unpack(WINSIZEFMT, winsize)[:2] # row, col, xpix, ypix
        return max(l, 24), max(c, 80)
    else:
        return 24, 80 
Example #23
Source File: proctools.py    From pycopia with Apache License 2.0 5 votes vote down vote up
def isatty(self):
        return os.isatty(self._fd) 
Example #24
Source File: proctools.py    From pycopia with Apache License 2.0 5 votes vote down vote up
def isatty(self):
        return os.isatty(self._p_stdin) 
Example #25
Source File: expect.py    From pycopia with Apache License 2.0 5 votes vote down vote up
def isatty(self):
        return os.isatty(self._fo.fileno()) 
Example #26
Source File: ANSIterm.py    From pycopia with Apache License 2.0 5 votes vote down vote up
def get_ansiterm(fo, rows=24, cols=80, printer=None):
    screen = ANSIScreen(rows, cols)
    kb = ANSIKeyboard()
    t = ANSITerminal(fo, screen=screen, printer=printer, keyboard=kb)
    if os.isatty(fo.fileno()):
        from pycopia import tty
        tty.set_winsize(fo.fileno(), rows, cols)
    return t 
Example #27
Source File: dmidecode.py    From citellus with GNU General Public License v3.0 5 votes vote down vote up
def profile():
    """
    Parse output from dmidecode dump or tool
    """
    if os.isatty(sys.stdin.fileno()):
        content = _get_output()
    else:
        content = sys.stdin.read()

    info = parse_dmi(content)
    _show(info) 
Example #28
Source File: pty_spawn.py    From pipenv with MIT License 5 votes vote down vote up
def getecho(self):
        '''This returns the terminal echo mode. This returns True if echo is
        on or False if echo is off. Child applications that are expecting you
        to enter a password often set ECHO False. See waitnoecho().

        Not supported on platforms where ``isatty()`` returns False.  '''
        return self.ptyproc.getecho() 
Example #29
Source File: pty_spawn.py    From pipenv with MIT License 5 votes vote down vote up
def isatty(self):
        '''This returns True if the file descriptor is open and connected to a
        tty(-like) device, else False.

        On SVR4-style platforms implementing streams, such as SunOS and HP-UX,
        the child pty may not appear as a terminal device.  This means
        methods such as setecho(), setwinsize(), getwinsize() may raise an
        IOError. '''

        return os.isatty(self.child_fd) 
Example #30
Source File: ptyprocess.py    From pipenv with MIT License 5 votes vote down vote up
def setecho(self, state):
        '''This sets the terminal echo mode on or off. Note that anything the
        child sent before the echo will be lost, so you should be sure that
        your input buffer is empty before you call setecho(). For example, the
        following will work as expected::

            p = pexpect.spawn('cat') # Echo is on by default.
            p.sendline('1234') # We expect see this twice from the child...
            p.expect(['1234']) # ... once from the tty echo...
            p.expect(['1234']) # ... and again from cat itself.
            p.setecho(False) # Turn off tty echo
            p.sendline('abcd') # We will set this only once (echoed by cat).
            p.sendline('wxyz') # We will set this only once (echoed by cat)
            p.expect(['abcd'])
            p.expect(['wxyz'])

        The following WILL NOT WORK because the lines sent before the setecho
        will be lost::

            p = pexpect.spawn('cat')
            p.sendline('1234')
            p.setecho(False) # Turn off tty echo
            p.sendline('abcd') # We will set this only once (echoed by cat).
            p.sendline('wxyz') # We will set this only once (echoed by cat)
            p.expect(['1234'])
            p.expect(['1234'])
            p.expect(['abcd'])
            p.expect(['wxyz'])


        Not supported on platforms where ``isatty()`` returns False.
        '''
        _setecho(self.fd, state)

        self.echo = state