Python sys.stdout 模块,isatty() 实例源码

我们从Python开源项目中,提取了以下12个代码示例,用于说明如何使用sys.stdout.isatty()

项目:py    作者:pytest-dev    | 项目源码 | 文件源码
def __init__(self, file=None, stringio=False, encoding=None):
        if file is None:
            if stringio:
                self.stringio = file = py.io.TextIO()
            else:
                from sys import stdout as file
        elif py.builtin.callable(file) and not (
             hasattr(file, "write") and hasattr(file, "flush")):
            file = WriteFile(file, encoding=encoding)
        if hasattr(file, "isatty") and file.isatty() and colorama:
            file = colorama.AnsiToWin32(file).stream
        self.encoding = encoding or getattr(file, 'encoding', "utf-8")
        self._file = file
        self.hasmarkup = should_do_markup(file)
        self._lastlen = 0
        self._chars_on_current_line = 0
项目:dit    作者:filipelbc    | 项目源码 | 文件源码
def _flush_stdout():
    # This is needed before using stderr, since it is never buffered
    if not stdout.isatty():
        stdout.flush()
项目:fieldsight-kobocat    作者:awemulya    | 项目源码 | 文件源码
def process_response(self, request, response):
        from sys import stdout
        if stdout.isatty():
            for query in connection.queries:
                print "\033[1;31m[%s]\033[0m \033[1m%s\033[0m" % (
                    query['time'], " ".join(query['sql'].split()))

        return response
项目:upvm    作者:ryran    | 项目源码 | 文件源码
def check_prompt_root_pw():
    if not cfg.opts.root_password:
        if stdout.isatty():
            # If have tty, prompt for pass
            while True:
                passwd = raw_input(c.CYAN("Enter root password for new VM or enter '") + c.BOLD("random") + c.CYAN("' or '") + c.BOLD("disabled") + c.CYAN("' or file path : "))
                if passwd:
                    break
            cfg.opts.root_password = ''
            if passwd == 'random':
                c.verbose("Password for root will be randomly generated")
            elif passwd == 'disabled':
                c.verbose("Password auth for root will be disabled")
            elif os.path.isfile(os.path.expanduser(passwd)):
                passwd = os.path.expanduser(passwd)
                c.verbose("Password for root will be set by reading first line of file '{}'".format(passwd))
                cfg.opts.root_password = 'file:'
            else:
                c.verbose("Password for root will be set to string '{}'".format(passwd))
                cfg.opts.root_password = 'password:'
            cfg.opts.root_password += passwd
            save_passwd = raw_input(c.CYAN("Save password choice as default to '{}'? ".format(cfg.cfgfileUser)) + c.BOLD("[y]/n") + c.CYAN(" : "))
            if save_passwd != 'n':
                subprocess.call(['mkdir', '-p', os.path.dirname(os.path.expanduser(cfg.cfgfileUser))])
                with open(os.path.expanduser(cfg.cfgfileUser), 'a+') as f:
                    f.write('# Added by {}:\nroot-password = {}\n'.format(cfg.prog, cfg.opts.root_password))
                c.verbose("Wrote 'root-password = {}' to {}".format(cfg.opts.root_password, cfg.cfgfileUser))
        else:
            print(c.RED("No root password specified; aborting"))
            print("Either run with stdin/stdout connected to tty to interactively enter password or\n"
                  "  Use '--root-password password:PASSWORDSTRING' or\n"
                  "  Use '--root-password file:PASSWORDFILE' or\n"
                  "  Use '--root-password random'\n"
                  "  Note that any of these can be specified in config file as well")
            exit(1)
项目:upvm    作者:ryran    | 项目源码 | 文件源码
def check_prompt_vm_name():
    if cfg.opts.vmname:
        # If specified on cmdline, use it
        pass
    else:
        # Otherwise generate a guess
        _default_name = re.sub('[.]', '', cfg.opts.templateName)
        if stdout.isatty():
            # If have tty, prompt with default guess
            cfg.opts.vmname = raw_input(c.CYAN("Enter VMNAME ") + c.BOLD("[{}]".format(_default_name)) + c.CYAN(" : "))
            if not cfg.opts.vmname:
                cfg.opts.vmname = _default_name
        else:
            # If no tty, use default guess
            print(c.yellow("VMNAME not specified; using '{}'".format(_default_name)))
            cfg.opts.vmname = _default_name
    # Validate selected guest name
    while True:
        match = re.search(r'^{}$'.format(cfg.opts.vmname), cfg.guestList, re.M)
        if match:
            print(c.YELLOW("Already have a VM with the name '{}'".format(cfg.opts.vmname)))
            print(c.BOLD("\nExisting VMs:"))
            print(c.cyan(cfg.guestList.strip()))
            if not stdout.isatty():
                exit(1)
            cfg.opts.vmname = raw_input(c.CYAN("Enter a unique VM name : "))
        else:
            break
项目:upvm    作者:ryran    | 项目源码 | 文件源码
def check_prompt_hostname():
    if not cfg.opts.hostname:
        _default_name = '{}.{}'.format(re.sub('[.]', '', cfg.opts.vmname), cfg.opts.dnsdomain)
        if cfg.opts.hostname_prompt and stdout.isatty():
            cfg.opts.hostname = raw_input(c.CYAN("Enter HOSTNAME ") + c.BOLD("[{}]".format(_default_name)) + c.CYAN(" or ") + c.BOLD("!") + c.CYAN(" to skip changing hostname : "))
            if not cfg.opts.hostname:
                cfg.opts.hostname = _default_name
        else:
            c.verbose("HOSTNAME not specified; using '{}'".format(_default_name))
            cfg.opts.hostname = _default_name
项目:upvm    作者:ryran    | 项目源码 | 文件源码
def check_prompt_img_outfilepath():
    cfg.opts.outFile = '{}/{}'.format(cfg.opts.img_dir, cfg.opts.vmname)
    if cfg.opts.img_format in 'qcow2':
        cfg.opts.outFile += '.qcow2'
    # Ensure image file doesn't exist
    while os.path.exists(cfg.opts.outFile):
        print(c.YELLOW("Already have an image file with the name '{}' (in dir '{}')".format(os.path.basename(cfg.opts.outFile), cfg.opts.img_dir)))
        if not stdout.isatty():
            exit(1)
        _x = raw_input(c.CYAN("\nEnter a unique image file name (not incl. path) : "))
        cfg.opts.outFile = '{}/{}'.format(cfg.opts.img_dir, _x)
项目:upvm    作者:ryran    | 项目源码 | 文件源码
def prompt_for_template_and_exit():
    if stdout.isatty():
        print(c.cyan("Press Ctrl-c to quit or Enter to see available virt-builder templates"))
        x = raw_input("")
        print(get_virt_builder_list())
        exit()
    else:
        exit(1)
项目:lbry-android    作者:lbryio    | 项目源码 | 文件源码
def setup_color(color):
    enable_out = (False if color == 'never' else
                  True if color == 'always' else
                  stdout.isatty())
    Out_Style.enable(enable_out)
    Out_Fore.enable(enable_out)

    enable_err = (False if color == 'never' else
                  True if color == 'always' else
                  stderr.isatty())
    Err_Style.enable(enable_err)
    Err_Fore.enable(enable_err)
项目:py    作者:pytest-dev    | 项目源码 | 文件源码
def should_do_markup(file):
    if os.environ.get('PY_COLORS') == '1':
        return True
    if os.environ.get('PY_COLORS') == '0':
        return False
    return hasattr(file, 'isatty') and file.isatty() \
           and os.environ.get('TERM') != 'dumb' \
           and not (sys.platform.startswith('java') and os._name == 'nt')
项目:FormShare    作者:qlands    | 项目源码 | 文件源码
def process_response(self, request, response):
        from sys import stdout
        if stdout.isatty():
            for query in connection.queries:
                print "\033[1;31m[%s]\033[0m \033[1m%s\033[0m" % (
                    query['time'], " ".join(query['sql'].split()))

        return response
项目:py    作者:pytest-dev    | 项目源码 | 文件源码
def ansi_print(text, esc, file=None, newline=True, flush=False):
    if file is None:
        file = sys.stderr
    text = text.rstrip()
    if esc and not isinstance(esc, tuple):
        esc = (esc,)
    if esc and sys.platform != "win32" and file.isatty():
        text = (''.join(['\x1b[%sm' % cod for cod in esc])  +
                text +
                '\x1b[0m')     # ANSI color code "reset"
    if newline:
        text += '\n'

    if esc and win32_and_ctypes and file.isatty():
        if 1 in esc:
            bold = True
            esc = tuple([x for x in esc if x != 1])
        else:
            bold = False
        esctable = {()   : FOREGROUND_WHITE,                 # normal
                    (31,): FOREGROUND_RED,                   # red
                    (32,): FOREGROUND_GREEN,                 # green
                    (33,): FOREGROUND_GREEN|FOREGROUND_RED,  # yellow
                    (34,): FOREGROUND_BLUE,                  # blue
                    (35,): FOREGROUND_BLUE|FOREGROUND_RED,   # purple
                    (36,): FOREGROUND_BLUE|FOREGROUND_GREEN, # cyan
                    (37,): FOREGROUND_WHITE,                 # white
                    (39,): FOREGROUND_WHITE,                 # reset
                    }
        attr = esctable.get(esc, FOREGROUND_WHITE)
        if bold:
            attr |= FOREGROUND_INTENSITY
        STD_OUTPUT_HANDLE = -11
        STD_ERROR_HANDLE = -12
        if file is sys.stderr:
            handle = GetStdHandle(STD_ERROR_HANDLE)
        else:
            handle = GetStdHandle(STD_OUTPUT_HANDLE)
        oldcolors = GetConsoleInfo(handle).wAttributes
        attr |= (oldcolors & 0x0f0)
        SetConsoleTextAttribute(handle, attr)
        while len(text) > 32768:
            file.write(text[:32768])
            text = text[32768:]
        if text:
            file.write(text)
        SetConsoleTextAttribute(handle, oldcolors)
    else:
        file.write(text)

    if flush:
        file.flush()