本文整理汇总了Python中sys.stdout.isatty函数的典型用法代码示例。如果您正苦于以下问题:Python isatty函数的具体用法?Python isatty怎么用?Python isatty使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了isatty函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的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
示例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])
示例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)
示例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
示例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)
示例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)
示例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
示例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))
示例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
示例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']
示例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")
示例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)
示例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
示例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
示例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