sys.stdout.isatty

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.

200 Examples 7

Example 51

Project: TrustRouter
Source File: test_curses.py
View license
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()

Example 52

Project: conary
Source File: explain.py
View license
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 Documentation: %s\n" %
            _formatString('B{' + title + '}') + docString)

Example 53

Project: Contexts
Source File: cli.py
View license
    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

Example 54

Project: Ultros
Source File: console.py
View license
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

Example 55

Project: Arturo
Source File: filters.py
View license
@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'
    ])

Example 56

Project: pip
Source File: search.py
View license
    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

Example 57

Project: git-cvs
Source File: term.py
View license
    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

Example 58

Project: gerrymander
Source File: pager.py
View license
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

Example 59

Project: oioioi
Source File: __init__.py
View license
    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)

Example 60

Project: kafka-utils
Source File: __init__.py
View license
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)

Example 61

Project: clint
Source File: cols.py
View license
def _find_unix_console_width():
    import termios, fcntl, struct, sys

    # fcntl.ioctl will fail if stdout is not a tty
    if not sys.stdout.isatty():
        return None

    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

Example 62

Project: pgctl
Source File: cli.py
View license
    @classmethod
    def wrap(cls, text, style):
        if sys.stdout.isatty():
            return '{}{}{}'.format(style, text, cls.ENDC)
        else:
            return text

Example 63

Project: twitter
Source File: ansi.py
View license
    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 ""

Example 64

Project: colorclass
Source File: codes.py
View license
    @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

Example 65

Project: python-for-android
Source File: logger.py
View license
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)

Example 66

View license
    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")

Example 67

Project: kbengine
Source File: search.py
View license
    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

Example 68

Project: luigi
Source File: notifications.py
View license
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

Example 69

Project: kbengine
Source File: search.py
View license
    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

Example 70

Project: utter-va
Source File: ansi.py
View license
    def cmdReset(self):
        ''' Returns the ansi cmd colour for a RESET '''
        if sys.stdout.isatty() or self.forceAnsi:
            return ESC + "[0m"
        else:
            return ""

Example 71

Project: clint
Source File: colored.py
View license
    @property
    def color_str(self):
        style = 'BRIGHT' if self.bold else 'NORMAL'
        c = '%s%s%s%s%s' % (getattr(colorama.Fore, self.color), getattr(colorama.Style, style), self.s, colorama.Fore.RESET, getattr(colorama.Style, 'NORMAL'))

        if self.always_color:
            return c
        elif sys.stdout.isatty() and not DISABLE_COLOR:
            return c
        else:
            return self.s

Example 72

Project: utter-va
Source File: ansi.py
View license
    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 ""

Example 73

Project: ansible
Source File: __init__.py
View license
    def pager(self, text):
        ''' find reasonable way to display text '''
        # this is a much simpler form of what is in pydoc.py
        if not sys.stdout.isatty():
            display.display(text)
        elif 'PAGER' in os.environ:
            if sys.platform == 'win32':
                display.display(text)
            else:
                self.pager_pipe(text, os.environ['PAGER'])
        else:
            p = subprocess.Popen('less --version', shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
            p.communicate()
            if p.returncode == 0:
                self.pager_pipe(text, 'less')
            else:
                display.display(text)

Example 74

Project: simple-data
Source File: search.py
View license
    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

Example 75

Project: subuser
Source File: runtime.py
View license
  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"]

Example 76

Project: alchemist
Source File: management.py
View license
    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)

Example 77

Project: lnst
Source File: Logs.py
View license
    def _decorate_value(self, string, preset):
        value = strip_colours(string)
        if sys.stdout.isatty() and self._coloured:
            return decorate_with_preset(value, preset)
        else:
            return value

Example 78

Project: nginx-python-buildpack
Source File: search.py
View license
    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

Example 79

Project: fabulous
Source File: term.py
View license
    def __init__(self, stream):
        import curses
        self.curses = curses
        UnixTerm.__init__(self, stream)
        if not sys.stdout.isatty(): return
        self.curses.setupterm()

Example 80

Project: datacats
Source File: main.py
View license
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)

Example 81

Project: lnst
Source File: Logs.py
View license
    def _decorate_value(self, string, preset):
        value = strip_colours(string)
        if sys.stdout.isatty() and self._coloured:
            return decorate_with_preset(value, preset)
        else:
            return value

Example 82

Project: cement
Source File: ext_colorlog.py
View license
    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

Example 83

Project: python-gflags
Source File: _helpers.py
View license
def GetHelpWidth():
  """Returns: an integer, the width of help lines that is used in TextWrap."""
  if not sys.stdout.isatty() or termios is None or fcntl is None:
    return _DEFAULT_HELP_WIDTH
  try:
    data = fcntl.ioctl(sys.stdout, termios.TIOCGWINSZ, '1234')
    columns = struct.unpack('hh', data)[1]
    # Emacs mode returns 0.
    # Here we assume that any value below 40 is unreasonable.
    if columns >= _MIN_HELP_WIDTH:
      return columns
    # Returning an int as default is fine, int(int) just return the int.
    return int(os.getenv('COLUMNS', _DEFAULT_HELP_WIDTH))

  except (TypeError, IOError, struct.error):
    return _DEFAULT_HELP_WIDTH

Example 84

Project: sacad
Source File: recurse.py
View license
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

Example 85

Project: dash-hack
Source File: table_formatter.py
View license
def detectHtmlOutputType(requestedType):
    if requestedType == "txt":
        return False
    elif requestedType in ["html", "moinwiki"]:
        return True
    else:
        if sys.stdout.isatty():
            return False
        else:
            outname = getStdoutFilename()
            if outname:
                if outname.endswith(".htm") or outname.endswith(".html"):
                    return True
                else:
                    return False
            else:
                return False

Example 86

Project: pre-commit
Source File: color.py
View license
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())
    )

Example 87

Project: beets-check
Source File: check.py
View license
    def log_progress(self, msg, index, total):
        if self.quiet or not sys.stdout.isatty():
            return
        msg = u'{}: {}/{} [{}%]'.format(msg, index, total, index*100/total)
        sys.stdout.write(msg + '\r')
        sys.stdout.flush()
        if index == total:
            sys.stdout.write('\n')
        else:
            sys.stdout.write(len(msg)*' ' + '\r')

Example 88

Project: zk_shell
Source File: xcmd.py
View license
    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)

Example 89

Project: ansible
Source File: __init__.py
View license
    def pager(self, text):
        ''' find reasonable way to display text '''
        # this is a much simpler form of what is in pydoc.py
        if not sys.stdout.isatty():
            display.display(text)
        elif 'PAGER' in os.environ:
            if sys.platform == 'win32':
                display.display(text)
            else:
                self.pager_pipe(text, os.environ['PAGER'])
        else:
            p = subprocess.Popen('less --version', shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
            p.communicate()
            if p.returncode == 0:
                self.pager_pipe(text, 'less')
            else:
                display.display(text)

Example 90

Project: termstyle
Source File: termstyle.py
View license
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

Example 91

Project: ganeti
Source File: colors.py
View license
def check_for_colors():
  """Tries to call 'tput' to properly determine, if the terminal has colors.

  This functions is meant to be run once at the program's start. If not
  invoked, colors are enabled iff standard output is a terminal.
  """
  colors = 0
  if sys.stdout.isatty():
    try:
      p = subprocess.Popen(["tput", "colors"], stdout=subprocess.PIPE)
      output = p.communicate()[0]
      if p.returncode == 0:
        colors = int(output)
    except (OSError, ValueError):
      pass
  global _enabled
  _enabled = (colors >= 2)

Example 92

Project: pip-update-requirements
Source File: search.py
View license
    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

Example 93

Project: Flask
Source File: search.py
View license
    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

Example 94

Project: Cnchi
Source File: pkginfo.py
View license
def get_term_size():
    if sys.stdout.isatty():
        height, width = struct.unpack("HH", fcntl.ioctl(1, termios.TIOCGWINSZ, 4 * b"\x00"))
        return width
    else:
        return 80

Example 95

Project: Cnchi
Source File: pkginfo.py
View license
def get_term_size():
    if sys.stdout.isatty():
        height, width = struct.unpack("HH", fcntl.ioctl(1, termios.TIOCGWINSZ, 4 * b"\x00"))
        return width
    else:
        return 80

Example 96

Project: dotbot
Source File: messenger.py
View license
    def _reset(self):
        '''
        Get a reset color (terminal escape sequence).
        '''
        if not sys.stdout.isatty():
            return ''
        else:
            return Color.RESET

Example 97

Project: pycarddav
Source File: model.py
View license
    def _pretty_base(self, keylist):
        collector = list()
        if sys.stdout.isatty():
            collector.append('\n' + BTEXT + 'Name: ' + self.fname + NTEXT)
        else:
            collector.append('\n' + 'Name: ' + self.fname)
        for key in keylist:
            for value in self[key]:
                try:
                    types = ' (' + ', '.join(value[1]['TYPE']) + ')'
                except KeyError:
                    types = ''
                line = key + types + ': ' + value[0]
                collector.append(line)
        return '\n'.join(collector)

Example 98

Project: seqmagick
Source File: quality_filter.py
View license
    def _report(self):
        if not sys.stdout.isatty():
            return
        t = time.time()
        if t - self.last_report < 0.4 or not self.read:
            return

        self.last_report = t
        sys.stderr.write('{0:10.1f}s Processed {1:10d} records; {2:10d} passed ({3:6.2f}%)\r'.format(
            t - self.start,
            self.read,
            self.read - self.failed,
            float(self.read - self.failed) / self.read * 100.0))

Example 99

Project: did
Source File: utils.py
View license
    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

Example 100

Project: scrapy
Source File: display.py
View license
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