Here are the examples of the python api sys.stdout.isatty taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
153 Examples
4
Example 1
Project: battery-status Source File: battery-status-graph.py
def render_graph():
if sys.stdout.isatty() and args.outfile == sys.stdout:
logging.info("drawing on tty")
plt.show()
else:
logging.info('drawing to file %s', args.outfile)
plt.savefig(args.outfile, bbox_inches='tight')
3
Example 2
def __init__(self, name=""):
self.barsToProgress = {}
self.t0 = time.time()
self.timeRemaining = "--"
self.status = "+"
self.name = name
self.lastRedraw = time.time()
self.isatty = sys.stdout.isatty()
try:
self.handleResize(None,None)
signal.signal(signal.SIGWINCH, self.handleResize)
self.signal_set = True
except:
self.term_width = 79
3
Example 3
Project: taurus Source File: test_consoleStatusReporter.py
def test_screen(self):
obj = ConsoleStatusReporter()
obj.settings["screen"] = "console"
if not sys.stdout.isatty():
self.assertEqual(obj._get_screen_type(), "dummy")
elif is_windows():
self.assertEqual(obj._get_screen(), "gui")
else:
self.assertEqual(obj._get_screen_type(), "console")
3
Example 4
Project: cement Source File: ext_colorlog.py
def _get_console_format(self):
format = super(ColorLogHandler, self)._get_console_format()
colorize = self.app.config.get('log.colorlog', 'colorize_console_log')
if sys.stdout.isatty() or 'CEMENT_TEST' in os.environ:
if is_true(colorize):
format = "%(log_color)s" + format
return format
3
Example 5
Project: kafka-utils Source File: __init__.py
def format_to_json(data):
"""Converts `data` into json
If stdout is a tty it performs a pretty print.
"""
if sys.stdout.isatty():
return json.dumps(data, indent=4, separators=(',', ': '))
else:
return json.dumps(data)
3
Example 6
def cmdReset(self):
''' Returns the ansi cmd colour for a RESET '''
if sys.stdout.isatty() or self.forceAnsi:
return ESC + "[0m"
else:
return ""
3
Example 7
def progress(rest=None, every=1):
global g_currentProgress, g_numProgress
if not sys.stdout.isatty():
return
if rest:
g_numProgress += 1
g_currentProgress = rest
if g_numProgress % every == 0:
print("\r% 6d %s " % (g_numProgress, rest), end="")
sys.stdout.flush()
else:
g_currentProgress = ""
g_numProgress = 0
print()
sys.stdout.flush()
3
Example 8
def write(pri, message):
""" Record a log message.
Currently just uses syslog, and if unattended, writes the log messages
to stdout so they can be piped elsewhere.
"""
syslog.openlog('pakrat') # sets log ident
syslog.syslog(pri, message)
if not sys.stdout.isatty():
print message # print if running unattended
3
Example 9
Project: upvm Source File: finalprompter.py
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)
3
Example 10
Project: sacad Source File: recurse.py
def show_get_covers_progress(current_idx, total_count, stats, *, artist=None, album=None, end=False):
""" Display search and download global progress. """
if not sys.stdout.isatty():
return
line_width = shutil.get_terminal_size(fallback=(80, 0))[0] - 1
print(" " * line_width, end="\r")
print("Searching and downloading covers %u%% (%u/%u)%s | %s" % (100 * current_idx // total_count,
current_idx,
total_count,
(" | Current album: '%s' '%s'" % (artist, album)) if not end else "",
" ".join(("%u %s" % (v, k)) for k, v in stats.items())),
end="\r" if not end else "\n")
3
Example 11
Project: plumbum Source File: styles.py
def get_color_repr():
"""Gets best colors for current system."""
if not sys.stdout.isatty():
return False
term =local.env.get("TERM", "")
# Some terminals set TERM=xterm for compatibility
if term.endswith("256color") or term == "xterm":
return 3 if platform.system() == 'Darwin' else 4
elif term.endswith("16color"):
return 2
elif term == "screen":
return 1
elif os.name == 'nt':
return 0
else:
return 3
3
Example 12
def get_pager():
if not sys.stdout.isatty():
return None
pager = get_pager_env("GERRYMANDER_PAGER")
if not pager:
pager = get_pager_env("PAGER")
if not pager:
pager = "less"
if pager == "cat":
return None
return pager
3
Example 13
Project: scrapy Source File: display.py
def _colorize(text, colorize=True):
if not colorize or not sys.stdout.isatty():
return text
try:
from pygments import highlight
from pygments.formatters import TerminalFormatter
from pygments.lexers import PythonLexer
return highlight(text, PythonLexer(), TerminalFormatter())
except ImportError:
return text
3
Example 14
@classmethod
def wrap(cls, text, style):
if sys.stdout.isatty():
return '{}{}{}'.format(style, text, cls.ENDC)
else:
return text
3
Example 15
Project: livecd-tools Source File: fs.py
def mksquashfs(in_img, out_img, compress_type):
# Allow gzip to work for older versions of mksquashfs
if not compress_type or compress_type == "gzip":
args = ["/sbin/mksquashfs", in_img, out_img]
else:
args = ["/sbin/mksquashfs", in_img, out_img, "-comp", compress_type]
if not sys.stdout.isatty():
args.append("-no-progress")
ret = call(args)
if ret != 0:
raise SquashfsError("'%s' exited with error (%d)" %
(string.join(args, " "), ret))
3
Example 16
def colorize(level, message):
# if not in a tty, we're likely redirected or piped
if not sys.stdout.isatty():
return message
# color mappings
colors = {
"CRITICAL": RED,
"ERROR": RED,
"WARNING": YELLOW,
"INFO": GREEN,
"DEBUG": BLUE,
"NOTSET": END,
}
# colored string
return "".join([colors[level], message, END])
3
Example 17
Project: luigi Source File: notifications.py
def _email_disabled_reason():
if email().format == 'none':
return "email format is 'none'"
elif email().force_send:
return None
elif sys.stdout.isatty():
return "running from a tty"
else:
return None
3
Example 18
Project: alchemist Source File: management.py
def __init__(self, app, **kwargs):
# Initialize color output.
if sys.stdout.isatty(): # pragma: nocoverage
colorama.init()
# Disable loading of default flask-script commands.
kwargs.setdefault('with_default_commands', False)
super(Manager, self).__init__(app, **kwargs)
# Discover commands using the flask-components utility.
for component in components.find('commands', app):
for command in component.values():
if (command and isinstance(command, type) and
issubclass(command, (script.Command, script.Manager))):
self.add_command(command)
3
Example 19
Project: pip Source File: search.py
def run(self, options, args):
if not args:
raise CommandError('Missing required argument (search query).')
query = args
pypi_hits = self.search(query, options)
hits = transform_hits(pypi_hits)
terminal_width = None
if sys.stdout.isatty():
terminal_width = get_terminal_size()[0]
print_results(hits, terminal_width=terminal_width)
if pypi_hits:
return SUCCESS
return NO_MATCHES_FOUND
3
Example 20
Project: sacad Source File: recurse.py
def show_analyze_progress(stats, scrobbler, *, time_progress_shown=0, end=False):
""" Display analysis global progress. """
now = time.monotonic()
if (sys.stdout.isatty() and
(end or (now - time_progress_shown > 0.1))): # do not refresh display at each call (for performance)
time_progress_shown = now
print("Analyzing library %s | %s" % (next(scrobbler) if not end else "-",
" ".join(("%u %s" % (v, k)) for k, v in stats.items())),
end="\r" if not end else "\n")
return time_progress_shown
3
Example 21
Project: FedoraReview Source File: ansi.py
def color_supported():
''' Return true if we are running on color supporting terminal '''
try:
if sys.stdout.isatty() and sys.stderr.isatty():
curses.setupterm()
if curses.tigetnum("colors") != -1:
return True
return False
except AttributeError:
return False
except curses.error:
return False
3
Example 22
def initialise(self, args, env):
if not sys.stdout.isatty():
return False
if args.colour:
global colorama
try:
import colorama # noqa
except ImportError:
return False
return True
3
Example 23
def _run(self):
files = ["bugzilla/", "bin-bugzilla", "examples/*.py", "tests/*.py"]
output_format = sys.stdout.isatty() and "colorized" or "text"
cmd = "pylint "
cmd += "--output-format=%s " % output_format
cmd += " ".join(files)
os.system(cmd + " --rcfile tests/pylint.cfg")
print("running pep8")
cmd = "pep8 "
cmd += " ".join(files)
os.system(cmd + " --config tests/pep8.cfg --exclude oldclasses.py")
3
Example 24
Project: conary Source File: explain.py
def _pageDoc(title, docString):
docString = _formatDocString(docString)
# pydoc is fooled by conary's wrapping of stdout. override it if needed.
if sys.stdout.isatty():
if _useLess():
# -R parses CSR escape codes properly
pydoc.pager = lambda x: pydoc.pipepager(x, 'less -R')
else:
# PAGER is set if _useLess returns False
pydoc.pager = lambda x: pydoc.pipepager(x, os.environ['PAGER'])
pydoc.pager("Conary API Docuementation: %s\n" %
_formatString('B{' + title + '}') + docString)
3
Example 25
def __init__(self, connection, database, params=None, header=False, show_progress=False, clear_progress=False):
self.connection = connection
self.database = database
self._params = {} if params is None else params
self._header = header
if IPython and not sys.stdout.isatty():
# Enable progress for IPython notebook
self.show_progress = show_progress
self.clear_progress = clear_progress
else:
self.show_progress = False
self.clear_progress = False
3
Example 26
def test_main():
if not sys.stdout.isatty():
raise unittest.SkipTest("sys.stdout is not a tty")
# testing setupterm() inside initscr/endwin
# causes terminal breakage
curses.setupterm(fd=sys.stdout.fileno())
try:
stdscr = curses.initscr()
main(stdscr)
finally:
curses.endwin()
unit_tests()
3
Example 27
def getTerminalSize():
if not sys.stdout.isatty():
raise Exception("This is not a TTY.")
import platform
current_os = platform.system()
tuple_xy = None
if current_os == 'Windows':
tuple_xy = _getTerminalSize_windows()
if tuple_xy is None:
tuple_xy = _getTerminalSize_tput()
# needed for window's python in cygwin's xterm!
if current_os == 'Linux' or current_os == 'Darwin' \
or current_os.startswith('CYGWIN'):
tuple_xy = _getTerminalSize_linux()
if tuple_xy is None:
raise Exception(_("Unable to get the size of this terminal."))
return tuple_xy
3
Example 28
@filter
def colorize(s, color):
if not sys.stdout.isatty():
return s
ccodes = {
'cyan': '96',
'purple': '95',
'blue': '94',
'green': '92',
'yellow': '93',
'red': '91',
}
return ''.join([
'\033[', ccodes[color], 'm',
s,
'\033[0m'
])
3
Example 29
def __init__(self):
self.last_progress = 0
self.last_message = ''
self.last_count = None
self.last_total = None
self.update_suppressed = False
if sys.stdout.isatty():
self.update_interval = 1
self.update = self.update_tty
self.finish = self.finish_tty
else:
self.update_interval = 30
self.update = self.update_dumb
self.finish = self.finish_dumb
3
Example 30
def show_output(self, fmt_str, *params, **kwargs):
""" MAX_OUTPUT chars of the last output is available via $? """
if PYTHON3:
fmt_str = str(fmt_str)
out = fmt_str % params if len(params) > 0 else fmt_str
if out is not None:
self._last_output = out if len(out) < MAX_OUTPUT else out[:MAX_OUTPUT]
if not PYTHON3 and not sys.stdout.isatty() and out:
out = out.encode('utf-8')
end = kwargs['end'] if 'end' in kwargs else '\n'
print(out, file=self._output, end=end)
3
Example 31
Project: paasta Source File: fsm.py
def write_paasta_config(variables, template, destination):
print "Using cookiecutter template from %s" % template
cookiecutter(
template=template,
extra_context=variables,
output_dir=destination,
overwrite_if_exists=True,
no_input=not sys.stdout.isatty(),
)
3
Example 32
def update(self, value=None, preserve=False):
"""Set new value (if given) and redraw the bar.
:param preserve: controls if bar will end with a new line and
stay after next update.
"""
if value:
if value > self.max_value:
raise ValueError(_("Too large value for progress bar"))
self.value = value
if sys.stdout.isatty():
self._clear()
self._show(preserve)
elif preserve:
self._show(preserve)
3
Example 33
Project: zdict Source File: zdict.py
def lookup_string_wrapper(dict_class, word, args):
import sys
if args.force_color:
utils.Color.set_force_color()
else:
utils.Color.set_force_color(sys.stdout.isatty())
dictionary = dict_class(args)
f = StringIO()
with redirect_stdout(f):
dictionary.lookup(word)
return f.getvalue()
3
Example 34
Project: PyClassLessons Source File: search.py
def run(self, options, args):
if not args:
raise CommandError('Missing required argument (search query).')
query = args
index_url = options.index
pypi_hits = self.search(query, index_url)
hits = transform_hits(pypi_hits)
terminal_width = None
if sys.stdout.isatty():
terminal_width = get_terminal_size()[0]
print_results(hits, terminal_width=terminal_width)
if pypi_hits:
return SUCCESS
return NO_MATCHES_FOUND
3
Example 35
Project: taurus Source File: test_consoleStatusReporter.py
def test_screen_invalid(self):
obj = ConsoleStatusReporter()
obj.settings["screen"] = "invalid"
if not sys.stdout.isatty():
self.assertEqual(obj._get_screen_type(), "dummy")
elif is_windows():
self.assertEqual(obj._get_screen(), "gui")
else:
self.assertEqual(obj._get_screen_type(), "console")
3
Example 36
Project: twitter Source File: ansi.py
def cmdColour(self, colour):
'''
Return the ansi cmd colour (i.e. escape sequence)
for the ansi `colour` value
'''
if sys.stdout.isatty() or self.forceAnsi:
return ESC + "[" + colour + "m"
else:
return ""
3
Example 37
Project: applib Source File: textui.py
def _find_unix_console_width():
import termios, fcntl, struct, sys
# fcntl.ioctl will fail if stdout is not a tty
if sys.stdout.isatty():
s = struct.pack("HHHH", 0, 0, 0, 0)
fd_stdout = sys.stdout.fileno()
size = fcntl.ioctl(fd_stdout, termios.TIOCGWINSZ, s)
height, width = struct.unpack("HHHH", size)[:2]
return width
else:
return None
3
Example 38
@classmethod
def disable_if_no_tty(cls):
"""Disable all colors only if there is no TTY available.
:return: True if colors are disabled, False if stderr or stdout is a TTY.
:rtype: bool
"""
if sys.stdout.isatty() or sys.stderr.isatty():
return False
cls.disable_all_colors()
return True
3
Example 39
def __call__(self, app, **kwargs):
text = pprint.pformat(dict(app.config))
if sys.stdout.isatty(): # pragma: nocoverage
text = pygments.highlight(
text, PythonLexer(), TerminalFormatter())
print(text)
3
Example 40
Project: subuser Source File: runtime.py
def getBasicFlags(self):
common = ["--rm"]
if self.getBackground():
return common + ["--cidfile",self.getCidFile()]
else:
if sys.stdout.isatty() and sys.stdin.isatty():
return common + ["-i","-t"]
else:
return common + ["-i"]
3
Example 41
Project: datacats Source File: main.py
def _error_exit(exception):
if sys.stdout.isatty():
# error message to have colors if stdout goes to shell
exception.pretty_print()
else:
print exception
sys.exit(1)
3
Example 42
Project: pre-commit Source File: color.py
def use_color(setting):
"""Choose whether to use color based on the command argument.
Args:
setting - Either `auto`, `always`, or `never`
"""
if setting not in COLOR_CHOICES:
raise InvalidColorSetting(setting)
return (
setting == 'always' or
(setting == 'auto' and sys.stdout.isatty())
)
3
Example 43
Project: cement Source File: ext_colorlog.py
def _get_console_formatter(self, format):
colorize = self.app.config.get('log.colorlog', 'colorize_console_log')
if sys.stdout.isatty() or 'CEMENT_TEST' in os.environ:
if is_true(colorize):
formatter = self._meta.formatter_class(
format,
log_colors=self._meta.colors
)
else:
formatter = self._meta.formatter_class_without_color(
format
)
else:
klass = self._meta.formatter_class_without_color # pragma: nocover
formatter = klass(format) # pragma: nocover
return formatter
3
Example 44
def auto():
"""set colouring on if STDOUT is a terminal device, off otherwise"""
try:
Style.enabled = False
Style.enabled = sys.stdout.isatty()
except (AttributeError, TypeError):
pass
3
Example 45
Project: upvm Source File: finalprompter.py
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
3
Example 46
Project: Django-facebook Source File: search.py
def run(self, options, args):
if not args:
logger.warn('ERROR: Missing required argument (search query).')
return
query = ' '.join(args)
index_url = options.index
pypi_hits = self.search(query, index_url)
hits = transform_hits(pypi_hits)
terminal_width = None
if sys.stdout.isatty():
terminal_width = get_terminal_size()[0]
print_results(hits, terminal_width=terminal_width)
3
Example 47
def enabled(self):
""" True if coloring is currently enabled """
# In auto-detection mode color enabled when terminal attached
if self._mode == COLOR_AUTO:
return sys.stdout.isatty()
return self._mode == COLOR_ON
3
Example 48
def show_features(core):
"""
Show the parsed features
"""
# set needed configuration
world.config.write_steps_once = True
if not sys.stdout.isatty():
world.config.no_ansi = True
runner = Runner(HookRegistry(), dry_run=True)
runner.start(core.features_to_run, marker="show")
return 0
3
Example 49
def runCommand(self, cfg, argSet, args, **kwargs):
showPasswords = argSet.pop('show-passwords', False)
showContexts = argSet.pop('show-contexts', False)
showLineOrigins = argSet.pop('show-files', False)
try:
prettyPrint = sys.stdout.isatty()
except AttributeError:
prettyPrint = False
cfg.setDisplayOptions(hidePasswords=not showPasswords,
showContexts=showContexts,
prettyPrint=prettyPrint,
showLineOrigins=showLineOrigins)
if argSet: return self.usage()
if (len(args) > 2):
return self.usage()
else:
cfg.display()
3
Example 50
def progress(self, section, i, n, msg):
if n is None:
i = str(i)
else:
i = '%s/%s'%(i,n)
if self.verbosity(section) == 0 and sys.stdout.isatty():
print '\r'+i, msg,
sys.stdout.flush()
if i == n:
self.needsnl = False
print
else:
self.needsnl = True