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 1

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

Example 2

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 3

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 4

Project: PyClassLessons
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 5

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

Example 6

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 7

Project: paasta
Source File: fsm.py
View license
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(),
    )

Example 8

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 9

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

Example 10

Project: livecd-tools
Source File: fs.py
View license
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))

Example 11

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 12

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

Example 13

Project: twitter
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 14

Project: python-bugzilla
Source File: setup.py
View license
    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")

Example 15

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 16

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

Example 17

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

Example 18

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 19

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

Example 20

Project: ants
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

Example 21

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

Example 22

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 23

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

Example 24

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 25

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 26

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

Example 27

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 28

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 29

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 30

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

Example 31

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

Example 32

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 33

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 34

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 35

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 36

Project: WAPT
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 37

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

Example 38

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 39

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 40

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

Example 41

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 42

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

Example 43

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 44

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

Example 45

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 46

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

Example 47

Project: simpleflow
Source File: logging_formatter.py
View license
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])

Example 48

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 49

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 50

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