当前位置: 首页>>代码示例>>Python>>正文


Python stdout.isatty方法代码示例

本文整理汇总了Python中sys.stdout.isatty方法的典型用法代码示例。如果您正苦于以下问题:Python stdout.isatty方法的具体用法?Python stdout.isatty怎么用?Python stdout.isatty使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在sys.stdout的用法示例。


在下文中一共展示了stdout.isatty方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: __init__

# 需要导入模块: from sys import stdout [as 别名]
# 或者: from sys.stdout import isatty [as 别名]
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
        self._width_of_current_line = 0 
开发者ID:pytest-dev,项目名称:py,代码行数:19,代码来源:terminalwriter.py

示例2: should_do_markup

# 需要导入模块: from sys import stdout [as 别名]
# 或者: from sys.stdout import isatty [as 别名]
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') 
开发者ID:pytest-dev,项目名称:py,代码行数:10,代码来源:terminalwriter.py

示例3: prompt_for_template_and_exit

# 需要导入模块: from sys import stdout [as 别名]
# 或者: from sys.stdout import isatty [as 别名]
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) 
开发者ID:ryran,项目名称:upvm,代码行数:10,代码来源:cfg.py

示例4: check_prompt_root_pw

# 需要导入模块: from sys import stdout [as 别名]
# 或者: from sys.stdout import isatty [as 别名]
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) 
开发者ID:ryran,项目名称:upvm,代码行数:37,代码来源:finalprompter.py

示例5: check_prompt_vm_name

# 需要导入模块: from sys import stdout [as 别名]
# 或者: from sys.stdout import isatty [as 别名]
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 
开发者ID:ryran,项目名称:upvm,代码行数:30,代码来源:finalprompter.py

示例6: check_prompt_hostname

# 需要导入模块: from sys import stdout [as 别名]
# 或者: from sys.stdout import isatty [as 别名]
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 
开发者ID:ryran,项目名称:upvm,代码行数:12,代码来源:finalprompter.py

示例7: check_prompt_img_outfilepath

# 需要导入模块: from sys import stdout [as 别名]
# 或者: from sys.stdout import isatty [as 别名]
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) 
开发者ID:ryran,项目名称:upvm,代码行数:13,代码来源:finalprompter.py

示例8: process_response

# 需要导入模块: from sys import stdout [as 别名]
# 或者: from sys.stdout import isatty [as 别名]
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 
开发者ID:awemulya,项目名称:kobo-predict,代码行数:10,代码来源:middleware.py

示例9: show_help

# 需要导入模块: from sys import stdout [as 别名]
# 或者: from sys.stdout import isatty [as 别名]
def show_help() -> None:
    """
    shows the help of aurman
    """
    # remove colors in case of not terminal
    if stdout.isatty():
        print(aurman_help)
    else:
        print(Colors.strip_colors(str(aurman_help)))
    sys.exit(0) 
开发者ID:polygamma,项目名称:aurman,代码行数:12,代码来源:main.py

示例10: show_version

# 需要导入模块: from sys import stdout [as 别名]
# 或者: from sys.stdout import isatty [as 别名]
def show_version() -> None:
    """
    shows the version of aurman
    """
    # remove colors in case of not terminal
    if stdout.isatty():
        aurman_note(expac("-Q", ["v"], ["aurman-git", "aurman"])[0])
    else:
        print(expac("-Q", ["v"], ["aurman-git", "aurman"])[0])
    sys.exit(0) 
开发者ID:polygamma,项目名称:aurman,代码行数:12,代码来源:main.py

示例11: concat_str

# 需要导入模块: from sys import stdout [as 别名]
# 或者: from sys.stdout import isatty [as 别名]
def concat_str(*args):
        # check whether to use colors, bold etc. or not
        if Colors.color == 1 or Colors.color == 0 and stdout.isatty():
            return ''.join([str(arg) for arg in args])
        else:
            return ''.join([str(arg) for arg in args[1:-1]]) 
开发者ID:polygamma,项目名称:aurman,代码行数:8,代码来源:coloring.py

示例12: print_opener

# 需要导入模块: from sys import stdout [as 别名]
# 或者: from sys.stdout import isatty [as 别名]
def print_opener() -> None:
        """
        This function draws a big GRINDER ASCII logo at startup.
        :return: None
        """
        init(strip=not stdout.isatty())
        cprint(figlet_format("GRINDER", font="cosmike"), "blue", attrs=["bold"]) 
开发者ID:sdnewhop,项目名称:grinder,代码行数:9,代码来源:asciiart.py

示例13: __init__

# 需要导入模块: from sys import stdout [as 别名]
# 或者: from sys.stdout import isatty [as 别名]
def __init__(self) -> None:
        self.enable(stdout.isatty()) 
开发者ID:openmaptiles,项目名称:openmaptiles-tools,代码行数:4,代码来源:perfutils.py

示例14: main

# 需要导入模块: from sys import stdout [as 别名]
# 或者: from sys.stdout import isatty [as 别名]
def main():
    import argparse

    try:
        import pyperclip
    except ImportError:
        pyperclip = None

    parser = argparse.ArgumentParser(description="PTPImg uploader")
    parser.add_argument('images', metavar='filename|url', nargs='+')
    parser.add_argument(
        '-k', '--api-key', default=os.environ.get('PTPIMG_API_KEY'),
        help='PTPImg API key (or set the PTPIMG_API_KEY environment variable)')
    if pyperclip is not None:
        parser.add_argument(
            '-n', '--dont-copy', action='store_false', default=True,
            dest='clipboard',
            help='Do not copy the resulting URLs to the clipboard')
    parser.add_argument(
        '-b', '--bbcode', action='store_true', default=False,
        help='Output links in BBCode format (with [img] tags)')
    parser.add_argument(
        '--nobell', action='store_true', default=False,
        help='Do not bell in a terminal on completion')

    args = parser.parse_args()

    if not args.api_key:
        parser.error('Please specify an API key')
    try:
        image_urls = upload(args.api_key, args.images)
        if args.bbcode:
            printed_urls = ['[img]{}[/img]'.format(image_url) for image_url in image_urls]
        else:
            printed_urls = image_urls
        print(*printed_urls, sep='\n')
        # Copy to clipboard if possible
        if getattr(args, 'clipboard', False):
            pyperclip.copy('\n'.join(image_urls))
        # Ring a terminal if we are in terminal and allowed to do this
        if not args.nobell and stdout.isatty():
            stdout.write('\a')
            stdout.flush()
    except (UploadFailed, ValueError) as e:
        parser.error(str(e)) 
开发者ID:theirix,项目名称:ptpimg-uploader,代码行数:47,代码来源:ptpimg_uploader.py

示例15: ansi_print

# 需要导入模块: from sys import stdout [as 别名]
# 或者: from sys.stdout import isatty [as 别名]
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() 
开发者ID:pytest-dev,项目名称:py,代码行数:54,代码来源:terminalwriter.py


注:本文中的sys.stdout.isatty方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。