當前位置: 首頁>>代碼示例>>Python>>正文


Python os.isatty方法代碼示例

本文整理匯總了Python中os.isatty方法的典型用法代碼示例。如果您正苦於以下問題:Python os.isatty方法的具體用法?Python os.isatty怎麽用?Python os.isatty使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在os的用法示例。


在下文中一共展示了os.isatty方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: _is_daemonized

# 需要導入模塊: import os [as 別名]
# 或者: from os import isatty [as 別名]
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())
        ) 
開發者ID:cherrypy,項目名稱:cherrypy,代碼行數:19,代碼來源:plugins.py

示例2: getuser

# 需要導入模塊: import os [as 別名]
# 或者: from os import isatty [as 別名]
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 
開發者ID:geomagpy,項目名稱:magpy,代碼行數:26,代碼來源:cred.py

示例3: disp_recs_json

# 需要導入模塊: import os [as 別名]
# 或者: from os import isatty [as 別名]
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)) 
開發者ID:cea-sec,項目名稱:ivre,代碼行數:19,代碼來源:ipinfo.py

示例4: size

# 需要導入模塊: import os [as 別名]
# 或者: from os import isatty [as 別名]
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 
開發者ID:edgedb,項目名稱:edgedb,代碼行數:19,代碼來源:term.py

示例5: write

# 需要導入模塊: import os [as 別名]
# 或者: from os import isatty [as 別名]
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 
開發者ID:ssokolow,項目名稱:fastdupes,代碼行數:24,代碼來源:fastdupes.py

示例6: size

# 需要導入模塊: import os [as 別名]
# 或者: from os import isatty [as 別名]
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 
開發者ID:QData,項目名稱:deepWordBug,代碼行數:23,代碼來源:tty.py

示例7: getecho

# 需要導入模塊: import os [as 別名]
# 或者: from os import isatty [as 別名]
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 
開發者ID:pypa,項目名稱:pipenv,代碼行數:19,代碼來源:ptyprocess.py

示例8: colorize

# 需要導入模塊: import os [as 別名]
# 或者: from os import isatty [as 別名]
def colorize(cmd):
    from os import isatty

    if isatty(1):
        template = '\033[36m>\033[m \033[32m{0}\033[m'
    else:
        template = '> {0}'

    return template.format(shellescape(cmd)) 
開發者ID:edmundmok,項目名稱:mealpy,代碼行數:11,代碼來源:venv_update.py

示例9: _check_interactive

# 需要導入模塊: import os [as 別名]
# 或者: from os import isatty [as 別名]
def _check_interactive(*descriptors):
    for desc in descriptors:
        try:
            if not isatty(desc.fileno()):
                return False
        except Exception:
            # Anything broken we are going to pretend this is not
            # interactive
            return False

    return True  # pragma: no cover 
開發者ID:calmjs,項目名稱:calmjs,代碼行數:13,代碼來源:ui.py

示例10: _column_max_default

# 需要導入模塊: import os [as 別名]
# 或者: from os import isatty [as 別名]
def _column_max_default(self):
    # 1 == stdout
    return -1 if os.isatty(1) else 80 
開發者ID:luci,項目名稱:recipes-py,代碼行數:5,代碼來源:report.py

示例11: color_string

# 需要導入模塊: import os [as 別名]
# 或者: from os import isatty [as 別名]
def color_string(cls, input_str):
        if os.isatty(0):
            out = re.sub(r"begin_(\w+)\(", lambda m: cls[m.group(1)].colored_begin(), input_str)
            out = re.sub(r"\).end_(\w+)", lambda m: cls[m.group(1)].colored_end(), out)
            return out
        else:
            return input_str 
開發者ID:Parrot-Developers,項目名稱:olympe,代碼行數:9,代碼來源:event_marker.py

示例12: main

# 需要導入模塊: import os [as 別名]
# 或者: from os import isatty [as 別名]
def main():
    fd = sys.stdin.fileno()
    locale.setlocale(locale.LC_ALL, '')
    encoding = locale.getpreferredencoding()

    print('os.isatty({0}) => {1}'.format(fd, os.isatty(fd)))
    print('locale.getpreferredencoding() => {0}'.format(encoding))

    display_conf(kind='pathconf',
                 names=os.pathconf_names,
                 getter=lambda name: os.fpathconf(fd, name))

    try:
        (iflag, oflag, cflag, lflag, ispeed, ospeed, cc
         ) = termios.tcgetattr(fd)
    except termios.error as err:
        print('stdin is not a typewriter: {0}'.format(err))
    else:
        display_bitmask(kind='Input Mode',
                        bitmap=BITMAP_IFLAG,
                        value=iflag)
        display_bitmask(kind='Output Mode',
                        bitmap=BITMAP_OFLAG,
                        value=oflag)
        display_bitmask(kind='Control Mode',
                        bitmap=BITMAP_CFLAG,
                        value=cflag)
        display_bitmask(kind='Local Mode',
                        bitmap=BITMAP_LFLAG,
                        value=lflag)
        display_ctl_chars(index=CTLCHAR_INDEX,
                          cc=cc)
        print('os.ttyname({0}) => {1}'.format(fd, os.ttyname(fd)))
        print('os.ctermid() => {0}'.format(os.ttyname(fd))) 
開發者ID:HoussemCharf,項目名稱:FunUtils,代碼行數:36,代碼來源:display-terminal-info.py

示例13: supports_ansi_escape_codes

# 需要導入模塊: import os [as 別名]
# 或者: from os import isatty [as 別名]
def supports_ansi_escape_codes(fd):
    """Returns whether the output device is capable of interpreting ANSI escape
    codes when :func:`print_` is used.

    Args:
        fd (int): file descriptor (e.g. ``sys.stdout.fileno()``)
    Returns:
        `bool`
    """

    if os.isatty(fd):
        return True

    if not is_win:
        return False

    # Check for cygwin/msys terminal
    handle = winapi._get_osfhandle(fd)
    if handle == winapi.INVALID_HANDLE_VALUE:
        return False

    if winapi.GetFileType(handle) != winapi.FILE_TYPE_PIPE:
        return False

    file_name = _get_file_name_for_handle(handle)
    match = re.match(
        "^\\\\(cygwin|msys)-[a-z0-9]+-pty[0-9]+-(from|to)-master$", file_name)
    return match is not None 
開發者ID:bugatsinho,項目名稱:bugatsinho.github.io,代碼行數:30,代碼來源:_print.py

示例14: displayhosts

# 需要導入模塊: import os [as 別名]
# 或者: from os import isatty [as 別名]
def displayhosts(recordsgen, out=sys.stdout, **kargs):
    """Displays (on `out`, by default `sys.stdout`) the Nmap scan
    results generated by `recordsgen`.

    """
    if isinstance(recordsgen, dict):
        recordsgen = [recordsgen]
    for record in recordsgen:
        displayhost(record, out=out, **kargs)
        if os.isatty(out.fileno()):
            input()
        else:
            out.write('\n') 
開發者ID:cea-sec,項目名稱:ivre,代碼行數:15,代碼來源:nmapout.py

示例15: displayfunction_json

# 需要導入模塊: import os [as 別名]
# 或者: from os import isatty [as 別名]
def displayfunction_json(cur, dbase, no_screenshots=False):
    if os.isatty(sys.stdout.fileno()):
        indent = 4
    else:
        indent = None
    for h in cur:
        for fld in ['_id', 'scanid']:
            try:
                del h[fld]
            except KeyError:
                pass
        for port in h.get('ports', []):
            if no_screenshots:
                for fname in ['screenshot', 'screendata']:
                    if fname in port:
                        del port[fname]
            elif 'screendata' in port:
                port['screendata'] = utils.encode_b64(
                    dbase.from_binary(port['screendata'])
                )
            for script in port.get('scripts', []):
                if 'masscan' in script and 'raw' in script['masscan']:
                    script['masscan']['raw'] = utils.encode_b64(
                        dbase.from_binary(
                            script['masscan']['raw']
                        )
                    )
        print(json.dumps(h, indent=indent,
                         default=dbase.serialize)) 
開發者ID:cea-sec,項目名稱:ivre,代碼行數:31,代碼來源:activecli.py


注:本文中的os.isatty方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。