• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Python stdout.isatty函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

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



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

示例1: check_prompt_vm_name

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:eprasad,项目名称:upvm,代码行数:28,代码来源:finalprompter.py


示例2: main

def main():
    # On very first run, we need to get osinfo-query db & virt-builder template list
    # If tabCacheDir already exists, to speed execution when tab-completing, this does nothing
    build_initial_cache()
    # Parse cmdline arguments (If tab-completing, execution stops before returning)
    # options namespace saved to cfg.opts
    argparser.parse()
    # Get possible os-variants and virt-builder --list output
    if not cfg.osvariantChoices:
        refresh_cache()
    # Test for all needed system commands, appropriate permissions
    from modules import sysvalidator

    sysvalidator.check_system_config()
    # Prompt user for any missing (required) input
    from modules import finalprompter

    finalprompter.prompt_final_checks()
    # Launch virt-builder
    from modules import builder

    builder.build()
    # Quit if requested
    if cfg.opts.build_image_only:
        exit()
    # Launch virt-install
    from modules import installer

    installer.install()
    # Optionally launch serial connection
    if cfg.opts.autoconsole and stdout.isatty():
        if cfg.opts.loglevel < 20:
            sleep(5.0)
        subprocess.call(["virsh", "console", cfg.opts.vmname])
开发者ID:Aftermath,项目名称:upvm,代码行数:34,代码来源:upvm.py


示例3: geturl

def geturl(url, dst):
    """YouTube Video download function"""
    print("\nSaving video to '%s'" % (dst))
    if stdout.isatty():
        return urlretrieve(url, dst, lambda nb, bs, fs, url=url: _reporthook(nb, bs, fs))
    else:
        return urlretrieve(url, dst)
开发者ID:vince-stark,项目名称:youtube-downloader,代码行数:7,代码来源:youtube_downloader.py


示例4: process_response

    def process_response(self, request, response):
        from sys import stdout
        if stdout.isatty():
            for query in connections['default'].queries :
                print "\033[1;31m[%s]\033[0m \033[1m%s\033[0m" % (query['time'],
 " ".join(query['sql'].split()))
        return response
开发者ID:Bartelo,项目名称:openjumo,代码行数:7,代码来源:middleware.py


示例5: report

    def report(self, scope, lines=0, level=1, is_tty=stdout.isatty()):
        if level >= len(utils.sev):
            level = len(utils.sev) - 1
        tmpstr = ""
        if self.count > 0:
            tmpstr += "%sFiles tested (%s):%s\n\t" % (utils.color['HEADER'], len(scope), utils.color['DEFAULT']) if is_tty else "File tested (%s):\n\t" % (len(scope))
            tmpstr += "%s\n" % "\n\t".join(scope)

            tmpstr += "%sFiles skipped (%s):%s" % (utils.color['HEADER'], len(self.skipped), utils.color['DEFAULT']) if is_tty else "File skipped (%s):\n\t" % (len(self.skipped))
            for (fname, reason) in self.skipped:
                tmpstr += "\n\t%s (%s)" % (fname, reason)

            tmpstr += "\n%sTest results:%s\n" % (utils.color['HEADER'], utils.color['DEFAULT']) if is_tty else "Test results:\n"

            for filename,issues in self.resstore.items():
                for lineno, issue_type, issue_text in issues:
                    if utils.sev.index(issue_type) >= level:
                        tmpstr += "%s>> %s\n - %s::%s%s\n" % (utils.color.get(issue_type, utils.color['DEFAULT']), issue_text, filename, lineno, utils.color['DEFAULT']) if is_tty else ">> %s\n - %s::%s\n" % (issue_text, filename, lineno)
                        for i in utils.mid_range(lineno, lines):
                            line = linecache.getline(filename, i)
                            #linecache returns '' if line does not exist
                            if line != '':
                                tmpstr += "\t%3d  %s" % (i, linecache.getline(filename, i))
            print(tmpstr)
        else:
            self.logger.error("no results to display - %s files scanned" % self.count)
开发者ID:tmcpeak,项目名称:bandit,代码行数:26,代码来源:result_store.py


示例6: check_prompt_root_pw

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:eprasad,项目名称:upvm,代码行数:35,代码来源:finalprompter.py


示例7: error

def error(string, is_tty=stdout.isatty()):
    """
    Red text.
    """
    if os.name == 'nt':
        is_tty = False
    return ('\033[31;1m' + string + '\033[0m') if is_tty else string
开发者ID:tapichu,项目名称:pyautotest,代码行数:7,代码来源:ansi.py


示例8: output

def output(data, show_links=False, show_headers=False, output_json=False):
    """Main output function used for printing to stdout. It will
    invoke helper output function using generator or list and output
    total number of Resources if needed."""

    # If we have generator and don't have to output JSON, we can
    # loop throught it and output one resource at a time while
    # keeping count of them, so we can output the total later
    if isinstance(data, types.GeneratorType) and not output_json:
        resources_count = 0
        for d in data:
            _output(d, show_links=show_links, show_headers=show_headers, output_json=output_json)
            resources_count += 1

    # For every other case, we are putting resources in a list (if
    # they are not already) and outputting them all at once
    else:
        if isinstance(data, types.GeneratorType):
            data = list(data)
        elif not isinstance(data, list):
            data = [data]

        _output(data, show_links=show_links, show_headers=show_headers, output_json=output_json)
        resources_count = len(data)

    if stdout.isatty() and not output_json:
        stdout.write('\nTotal number of Resources returned: {}\n'.format(resources_count))
开发者ID:stormpath,项目名称:stormpath-cli,代码行数:27,代码来源:output.py


示例9: highlight

def highlight(string, is_tty=stdout.isatty()):
    """
    Green text.
    """
    if os.name == 'nt':
        is_tty = False
    return ('\033[32;1m' + string + '\033[0m') if is_tty else string
开发者ID:tapichu,项目名称:pyautotest,代码行数:7,代码来源:ansi.py


示例10: search

    def search(self):
        """Main method to perform the search."""

        # initialize the calculations
        self._initialize()

        # if the queue is not set, perform a CPU search, else use
        # GPU-acceleration
        if self.queue is None:
            self._cpu_init()
            self._cpu_search()
        else:
            self._gpu_init()
            self._gpu_search()

        # perform an extra print line if the output is an interactive shell,
        # for proper output
        if _stdout.isatty():
            print()

        # make the accessible interaction space a Volume object, for easier
        # manipulation later
        accessible_interaction_space = \
                volume.Volume(self.data['accessible_interaction_space'], 
                        self.voxelspacing, self.data['origin'])

        return accessible_interaction_space, self.data['accessible_complexes'], self.data['violations']
开发者ID:JoaoRodrigues,项目名称:disvis,代码行数:27,代码来源:disvis.py


示例11: run

def run(
    paths,
    output=_I_STILL_HATE_EVERYTHING,
    recurse=core.flat,
    sort_by=lambda x : x,
    ls=core.ls,
    stdout=stdout,
):
    """
    Project-oriented directory and file information lister.

    """

    if output is _I_STILL_HATE_EVERYTHING:
        output = core.columnized if stdout.isatty() else core.one_per_line

    def _sort_by(thing):
        return not getattr(thing, "_always_sorts_first", False), sort_by(thing)

    contents = [
        path_and_children
        for path in paths or (project.from_path(FilePath(".")),)
        for path_and_children in recurse(path=path, ls=ls)
    ]
    for line in output(contents, sort_by=_sort_by):
        stdout.write(line)
        stdout.write("\n")
开发者ID:digideskio,项目名称:L,代码行数:27,代码来源:cli.py


示例12: prompt_for_template_and_exit

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:Aftermath,项目名称:upvm,代码行数:8,代码来源:cfg.py


示例13: process_response

 def process_response(request, response):
     """Reads the query data and prints it"""
     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:AmatanHead,项目名称:collective-blog,代码行数:8,代码来源:sql_logger.py


示例14: process_response

 def process_response(self, request, response):
     from sys import stdout
     from django.db import connection
     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()))
         print len(connection.queries)
     return response
开发者ID:Norore,项目名称:jebif-root,代码行数:9,代码来源:middleware.py


示例15: __call__

    def __call__(self, request):
        response = self.get_response(request)
        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:onaio,项目名称:onadata,代码行数:9,代码来源:middleware.py


示例16: __make_color

    def __make_color(color, text):
        """ Here's actual magic happen.

        Returns:
            str: Colored text
        """
        if stdout.isatty():
            return color + text + CmdColors.END
        return text
开发者ID:jakule,项目名称:andiff,代码行数:9,代码来源:sanity_check.py


示例17: print_table

    def print_table(self, alloc, entity, rows, only_these_fields, sort=False, transforms=None):
        # For printing out results in an ascii table or CSV format.
        if alloc.quiet:
            return
        if not rows:
            return

        if not isinstance(sort, list):
            sort = [sort]
        if not isinstance(only_these_fields, list):
            only_these_fields = [only_these_fields]

        only_these_fields = self.__get_only_these_fields(
            alloc, entity, rows, only_these_fields)
        field_names = only_these_fields[1::2]

        # Re-order the table, this changes the dict to a list i.e.
        # dict.items().
        rows = self.__get_sorted_rows(alloc, entity, rows, sort)
        if rows:
            rows2 = []
            for k_, row in rows:
                row = self.__get_row(
                    alloc, entity, row, only_these_fields, transforms)
                rows2.append(row)
            rows = rows2

        if alloc.csv:
            csv_table = csv.writer(sys.stdout, lineterminator="\n")
            for row in rows:
                csv_table.writerow([unicode(s).encode('utf-8') for s in row])

        else:
            table = PrettyTable()
            table.set_field_names(field_names)
            # table.field_names = field_names
            for label in field_names:
                if '$' in label:
                    table.set_field_align(label, "r")
                else:
                    table.set_field_align(label, "l")

            if stdout.isatty():
                proc = subprocess.Popen(
                    ['stty', 'size'], stdout=subprocess.PIPE, stderr=open("/dev/null", "w"))
                ret = proc.wait()
                if ret == 0:
                    height_, width = proc.communicate()[0].split()
                    width = int(width)
                    rows = self.__fit_rows_to_screen(
                        alloc, rows, field_names, width)
            for row in rows:
                table.add_row(row)
            print unicode(table.get_string(header=True)).encode('utf-8')
            # http://stackoverflow.com/questions/15793886/how-to-avoid-a-broken-pipe-error-when-printing-a-large-amount-of-formatted-data
            sys.stdout.flush()
开发者ID:mattcen,项目名称:alloc,代码行数:56,代码来源:alloc_output_handler.py


示例18: check_prompt_hostname

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:eprasad,项目名称:upvm,代码行数:10,代码来源:finalprompter.py


示例19: format

 def format(self, record):
     levelname = record.levelname
     msg = Formatter.format(self, record)
     if levelname in COLORS:
         if stdout.isatty():
             msg = COLORS[levelname] % msg
     else:
         print ("*" * 100, levelname, "(%s)" % type(levelname), "not in",
                 COLORS.keys())
     return msg
开发者ID:silpol,项目名称:tryton-bef,代码行数:10,代码来源:log.py


示例20: check_prompt_img_outfilepath

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:eprasad,项目名称:upvm,代码行数:11,代码来源:finalprompter.py



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python stdout.strip函数代码示例发布时间:2022-05-27
下一篇:
Python stdout.flush函数代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap