sys.stderr.isatty

Here are the examples of the python api sys.stderr.isatty taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

85 Examples 7

Example 1

Project: deepwalk
Source File: __main__.py
View license
def debug(type_, value, tb):
  if hasattr(sys, 'ps1') or not sys.stderr.isatty():
    sys.__excepthook__(type_, value, tb)
  else:
    import traceback
    import pdb
    traceback.print_exception(type_, value, tb)
    print(u"\n")
    pdb.pm()

Example 2

Project: pyspeckit
Source File: pyspeckit_script.py
View license
        def info(type, value, tb):
            if hasattr(sys, 'ps1') or not sys.stderr.isatty():
                # we are in interactive mode or we don't have a tty-like
                # device, so we call the default hook
                sys.__excepthook__(type, value, tb)
            else:
                import traceback, pdb
                # we are NOT in interactive mode, print the exception...
                traceback.print_exception(type, value, tb)
                print()
                # ...then start the debugger in post-mortem mode.
                pdb.pm()

Example 3

Project: youtube-dl
Source File: helper.py
View license
def report_warning(message):
    '''
    Print the message to stderr, it will be prefixed with 'WARNING:'
    If stderr is a tty file the 'WARNING:' will be colored
    '''
    if sys.stderr.isatty() and compat_os_name != 'nt':
        _msg_header = '\033[0;33mWARNING:\033[0m'
    else:
        _msg_header = 'WARNING:'
    output = '%s %s\n' % (_msg_header, message)
    if 'b' in getattr(sys.stderr, 'mode', '') or sys.version_info[0] < 3:
        output = output.encode(preferredencoding())
    sys.stderr.write(output)

Example 4

Project: youtube-dl
Source File: common.py
View license
    def _report_progress_status(self, msg, is_last_line=False):
        fullmsg = '[download] ' + msg
        if self.params.get('progress_with_newline', False):
            self.to_screen(fullmsg)
        else:
            if compat_os_name == 'nt':
                prev_len = getattr(self, '_report_progress_prev_line_length',
                                   0)
                if prev_len > len(fullmsg):
                    fullmsg += ' ' * (prev_len - len(fullmsg))
                self._report_progress_prev_line_length = len(fullmsg)
                clear_line = '\r'
            else:
                clear_line = ('\r\x1b[K' if sys.stderr.isatty() else '\r')
            self.to_screen(clear_line + fullmsg, skip_eol=not is_last_line)
        self.to_console_title('youtube-dl ' + msg)

Example 5

Project: bloom
Source File: util.py
View license
def custom_exception_handler(type, value, tb):
    global _pdb
    # Print traceback
    import traceback
    print_exc(traceback.format_exception(type, value, tb))
    if not _pdb or hasattr(sys, 'ps1') or not sys.stderr.isatty():
        pass
    else:
        # ...then start the debugger in post-mortem mode.
        import pdb
        pdb.set_trace()

Example 6

Project: script.module.youtube.dl
Source File: common.py
View license
    def _report_progress_status(self, msg, is_last_line=False):
        fullmsg = '[download] ' + msg
        if self.params.get('progress_with_newline', False):
            self.to_screen(fullmsg)
        else:
            if compat_os_name == 'nt':
                prev_len = getattr(self, '_report_progress_prev_line_length',
                                   0)
                if prev_len > len(fullmsg):
                    fullmsg += ' ' * (prev_len - len(fullmsg))
                self._report_progress_prev_line_length = len(fullmsg)
                clear_line = '\r'
            else:
                clear_line = ('\r\x1b[K' if sys.stderr.isatty() else '\r')
            self.to_screen(clear_line + fullmsg, skip_eol=not is_last_line)
        self.to_console_title('youtube-dl ' + msg)

Example 7

Project: mergepbx
Source File: mergepbx.py
View license
def install_pdb_exception_handler():
    def info(type, value, tb):
       if hasattr(sys, 'ps1') or not sys.stderr.isatty():
          # we are in interactive mode or we don't have a tty-like
          # device, so we call the default hook
          sys.__excepthook__(type, value, tb)
       else:
          import traceback, pdb
          # we are NOT in interactive mode, print the exception...
          traceback.print_exception(type, value, tb)
          print
          # ...then start the debugger in post-mortem mode.
          pdb.pm()

    sys.excepthook = info

Example 8

Project: mergepbx
Source File: __main__.py
View license
def install_pdb_exception_handler():
    def info(type, value, tb):
       if hasattr(sys, 'ps1') or not sys.stderr.isatty():
          # we are in interactive mode or we don't have a tty-like
          # device, so we call the default hook
          sys.__excepthook__(type, value, tb)
       else:
          import traceback, pdb
          # we are NOT in interactive mode, print the exception...
          traceback.print_exception(type, value, tb)
          print
          # ...then start the debugger in post-mortem mode.
          pdb.pm()

    sys.excepthook = info

Example 9

Project: mergepbx
Source File: test.py
View license
def install_pdb_exception_handler():
    def info(type, value, tb):
       if hasattr(sys, 'ps1') or not sys.stderr.isatty():
          # we are in interactive mode or we don't have a tty-like
          # device, so we call the default hook
          sys.__excepthook__(type, value, tb)
       else:
          import traceback, pdb
          # we are NOT in interactive mode, print the exception...
          traceback.print_exception(type, value, tb)
          print
          # ...then start the debugger in post-mortem mode.
          pdb.pm()

    sys.excepthook = info

Example 10

Project: metasync
Source File: util.py
View license
def install_pdb():
    def info(type, value, tb):
        if hasattr(sys, 'ps1') or not sys.stderr.isatty():
            # You are in interactive mode or don't have a tty-like
            # device, so call the default hook
            sys.__execthook__(type, value, tb)
        else:
            import traceback
            import pdb
            # You are not in interactive mode; print the exception
            traceback.print_exception(type, value, tb)
            print
            # ... then star the debugger in post-mortem mode
            pdb.pm()

    sys.excepthook = info

Example 11

Project: polyglot
Source File: __main__.py
View license
def debug(type_, value, tb):
  if hasattr(sys, 'ps1') or not sys.stderr.isatty():
    sys.__excepthook__(type_, value, tb)
  else:
    import traceback
    import pdb
    traceback.print_exception(type_, value, tb)
    print(u"\n")
    pdb.pm()

Example 12

Project: viewfinder
Source File: secrets.py
View license
def GetSharedSecretsManager(can_prompt=None):
  """Returns the shared secrets manager. Creates it from options if None.
  If can_prompt is None, determine automatically.
  """
  global _shared_secrets_manager
  if _shared_secrets_manager is None:
    _shared_secrets_manager = SecretsManager('shared', options.options.domain, options.options.secrets_dir)
    prompt = can_prompt if can_prompt is not None else sys.stderr.isatty()
    _shared_secrets_manager.Init(can_prompt=prompt)
  return _shared_secrets_manager

Example 13

Project: viewfinder
Source File: secrets.py
View license
def GetUserSecretsManager(can_prompt=None):
  """Returns the user secrets manager. Creates it from options if None.
  If can_prompt is None, determine automatically.
  Fails in --devbox=False mode.
  """
  assert options.options.devbox, 'User secrets manager is only available in --devbox mode.'

  global _user_secrets_manager
  if _user_secrets_manager is None:
    # Create the user secrets manager.
    _user_secrets_manager = SecretsManager('user', options.options.domain, options.options.user_secrets_dir)
    prompt = can_prompt if can_prompt is not None else sys.stderr.isatty()
    _user_secrets_manager.Init(can_prompt=prompt)
  return _user_secrets_manager

Example 14

Project: viewfinder
Source File: log.py
View license
def _stderr_supports_color():
    color = False
    if curses and sys.stderr.isatty():
        try:
            curses.setupterm()
            if curses.tigetnum("colors") > 0:
                color = True
        except Exception:
            pass
    return color

Example 15

Project: langchangetrack
Source File: dump_timeseries.py
View license
def debug(type_, value, tb):
    if hasattr(sys, 'ps1') or not sys.stderr.isatty():
        # we are in interactive mode or we don't have a tty-like device, so we
        # call the default hook
        sys.__excepthook__(type_, value, tb)
    else:
        import traceback
        import pdb
        # we are NOT in interactive mode, print the exception...
        traceback.print_exception(type_, value, tb)
        print("\n")
        # ...then start the debugger in post-mortem mode.
        pdb.pm()

Example 16

View license
def debug(type_, value, tb):
    if hasattr(sys, 'ps1') or not sys.stderr.isatty():
        # we are in interactive mode or we don't have a tty-like
        # device, so we call the default hook
        sys.__excepthook__(type_, value, tb)
    else:
        import traceback
        import pdb
        # we are NOT in interactive mode, print the exception...
        traceback.print_exception(type_, value, tb)
        print("\n")
        # ...then start the debugger in post-mortem mode.
        pdb.pm()

Example 17

Project: langchangetrack
Source File: dummy_regressor.py
View license
def debug(type_, value, tb):
    if hasattr(sys, 'ps1') or not sys.stderr.isatty():
        # we are in interactive mode or we don't have a tty-like
        # device, so we call the default hook
        sys.__excepthook__(type_, value, tb)
    else:
        import traceback
        import pdb
        # we are NOT in interactive mode, print the exception...
        traceback.print_exception(type_, value, tb)
        print("\n")
        # ...then start the debugger in post-mortem mode.
        pdb.pm()

Example 18

Project: langchangetrack
Source File: common_vocab.py
View license
def debug(type_, value, tb):
    if hasattr(sys, 'ps1') or not sys.stderr.isatty():
        # we are in interactive mode or we don't have a tty-like
        # device, so we call the default hook
        sys.__excepthook__(type_, value, tb)
    else:
        import traceback
        import pdb
        # we are NOT in interactive mode, print the exception...
        traceback.print_exception(type_, value, tb)
        print("\n")
        # ...then start the debugger in post-mortem mode.
        pdb.pm()

Example 19

Project: langchangetrack
Source File: freq_count.py
View license
def debug(type_, value, tb):
    if hasattr(sys, 'ps1') or not sys.stderr.isatty():
        # we are in interactive mode or we don't have a tty-like
        # device, so we call the default hook
        sys.__excepthook__(type_, value, tb)
    else:
        import traceback
        import pdb
        # we are NOT in interactive mode, print the exception...
        traceback.print_exception(type_, value, tb)
        print("\n")
        # ...then start the debugger in post-mortem mode.
        pdb.pm()

Example 20

Project: langchangetrack
Source File: pos_tag.py
View license
def debug(type_, value, tb):
    if hasattr(sys, 'ps1') or not sys.stderr.isatty():
        # we are in interactive mode or we don't have a tty-like
        # device, so we call the default hook
        sys.__excepthook__(type_, value, tb)
    else:
        import traceback
        import pdb
        # we are NOT in interactive mode, print the exception...
        traceback.print_exception(type_, value, tb)
        print("\n")
        # ...then start the debugger in post-mortem mode.
        pdb.pm()

Example 21

Project: youtube-dl-GUI
Source File: common.py
View license
    def _report_progress_status(self, msg, is_last_line=False):
        fullmsg = '[download] ' + msg
        if self.params.get('progress_with_newline', False):
            self.to_screen(fullmsg)
        else:
            if os.name == 'nt':
                prev_len = getattr(self, '_report_progress_prev_line_length',
                                   0)
                if prev_len > len(fullmsg):
                    fullmsg += ' ' * (prev_len - len(fullmsg))
                self._report_progress_prev_line_length = len(fullmsg)
                clear_line = '\r'
            else:
                clear_line = ('\r\x1b[K' if sys.stderr.isatty() else '\r')
            self.to_screen(clear_line + fullmsg, skip_eol=not is_last_line)
        self.to_console_title('youtube-dl ' + msg)

Example 22

Project: ifwechat
Source File: logger.py
View license
def enable_pretty_logging(logger, level='info'):
    """Turns on formatted logging output as configured.
    """
    logger.setLevel(getattr(logging, level.upper()))

    if not logger.handlers:
        # Set up color if we are in a tty and curses is installed
        color = False
        if curses and sys.stderr.isatty():
            try:
                curses.setupterm()
                if curses.tigetnum("colors") > 0:
                    color = True
            except:
                pass
        channel = logging.StreamHandler()
        channel.setFormatter(_LogFormatter(color=color))
        logger.addHandler(channel)

Example 23

Project: simple-data
Source File: log.py
View license
def _stderr_supports_color():
    color = False
    if curses and sys.stderr.isatty():
        try:
            curses.setupterm()
            if curses.tigetnum("colors") > 0:
                color = True
        except Exception:
            pass
    return color

Example 24

Project: postgresql-perf-tools
Source File: pg-top.py
View license
	def __init__(self):
		self.scr = None
		self.opts = None
		self.con = []

		self.paused = 0
		self.terminate = False

		self.mutex = threading.Lock()
		self.prev_time = 0

		if sys.stderr.isatty():
			sys.stderr = StringIO.StringIO()

		self.init_user_cols()

Example 25

Project: SimpleBookMarks
Source File: log.py
View license
def _stderr_supports_color():
    color = False
    if curses and sys.stderr.isatty():
        try:
            curses.setupterm()
            if curses.tigetnum("colors") > 0:
                color = True
        except Exception:
            pass
    return color

Example 26

Project: GoogleSpeech
Source File: colored_logging.py
View license
  def format(self, record):
    message = super().format(record)
    if sys.stderr.isatty() and not sys.platform.startswith("win32"):
      try:
        color_code = LEVEL_COLOR_MAPPING[record.levelno].value
        bold = LEVEL_BOLD_MAPPING[record.levelno]
      except KeyError:
        pass
      else:
        message = "\033[%u;%um%s\033[0m" % (int(bold), 30 + color_code, message)
    return message

Example 27

Project: hddfancontrol
Source File: colored_logging.py
View license
  def format(self, record):
    message = super().format(record)
    if sys.stderr.isatty() and not sys.platform.startswith("win32"):
      try:
        color_code = LEVEL_COLOR_MAPPING[record.levelno].value
        bold = LEVEL_BOLD_MAPPING[record.levelno]
      except KeyError:
        pass
      else:
        message = "\033[%u;%um%s\033[0m" % (int(bold), 30 + color_code, message)
    return message

Example 28

Project: sacad
Source File: colored_logging.py
View license
  def format(self, record):
    message = super().format(record)
    if sys.stderr.isatty() and not sys.platform.startswith("win32"):
      try:
        color_code = LEVEL_COLOR_MAPPING[record.levelno].value
        bold = LEVEL_BOLD_MAPPING[record.levelno]
      except KeyError:
        pass
      else:
        message = "\033[%u;%um%s\033[0m" % (int(bold), 30 + color_code, message)
    return message

Example 29

Project: citationhunt
Source File: utils.py
View license
    def progress(self, message):
        message = e(message)
        if not sys.stderr.isatty():
            return

        if self._mode == 'PROGRESS':
            print >>sys.stderr, '\r',
        print >>sys.stderr, message,
        self._mode = 'PROGRESS'

Example 30

Project: nudge
Source File: log.py
View license
def try_color_logging():
    """ If curses is available, and this process is running in a tty,
        try to enable color logging.
    """
    color = False
    if curses and sys.stderr.isatty():
        try:
            curses.setupterm()
            if curses.tigetnum("colors") > 0:
                color = True
        except:
            pass
    channel = logging.StreamHandler()
    channel.setFormatter(_LogFormatter(color=color))
    logging.getLogger().addHandler(channel)

Example 31

Project: google-apputils
Source File: debug.py
View license
def _DebugHandler(exc_class, value, tb):
  if not flags.FLAGS.pdb or hasattr(sys, 'ps1') or not sys.stderr.isatty():
    # we aren't in interactive mode or we don't have a tty-like
    # device, so we call the default hook
    old_excepthook(exc_class, value, tb)
  else:
    # Don't impose import overhead on apps that never raise an exception.
    import traceback
    import pdb
    # we are in interactive mode, print the exception...
    traceback.print_exception(exc_class, value, tb)
    sys.stdout.write('\n')
    # ...then start the debugger in post-mortem mode.
    pdb.pm()

Example 32

Project: titan
Source File: debug.py
View license
def _DebugHandler(exc_class, value, tb):
  if not flags.FLAGS.pdb or hasattr(sys, 'ps1') or not sys.stderr.isatty():
    # we aren't in interactive mode or we don't have a tty-like
    # device, so we call the default hook
    old_excepthook(exc_class, value, tb)
  else:
    # Don't impose import overhead on apps that never raise an exception.
    import traceback
    import pdb
    # we are in interactive mode, print the exception...
    traceback.print_exception(exc_class, value, tb)
    sys.stdout.write('\n')
    # ...then start the debugger in post-mortem mode.
    pdb.pm()

Example 33

Project: buttersink
Source File: SSHStore.py
View license
    def measureSize(self, diff, chunkSize):
        """ Spend some time to get an accurate size. """
        (toUUID, fromUUID) = self.toArg.diff(diff)
        isInteractive = sys.stderr.isatty()
        return self.toObj.diff(self._client.measureSize(
            toUUID,
            fromUUID,
            diff.size,
            chunkSize,
            isInteractive,
        ))

Example 34

Project: cider
Source File: log.py
View license
def _stderr_supports_color():
    color = False
    if curses and sys.stderr.isatty():
        try:
            curses.setupterm()
            if curses.tigetnum("colors") > 0:
                color = True
        except Exception:
            pass
    return color

Example 35

Project: cider
Source File: log.py
View license
def _stderr_supports_color():
    color = False
    if curses and sys.stderr.isatty():
        try:
            curses.setupterm()
            if curses.tigetnum("colors") > 0:
                color = True
        except Exception:
            pass
    return color

Example 36

Project: Ivoire
Source File: run.py
View license
def should_color(when):
    """
    Decide whether to color output.

    """

    if when == "auto":
        return sys.stderr.isatty()
    return when == "always"

Example 37

Project: Ivoire
Source File: run.py
View license
def should_color(when):
    """
    Decide whether to color output.

    """

    if when == "auto":
        return sys.stderr.isatty()
    return when == "always"

Example 38

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 39

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 40

Project: chopsticks
Source File: ioloop.py
View license
    def println(self, l):
        if not PY2:
            l = l.decode('utf8')
        if sys.stderr.isatty():
            fmt = '\x1b[31m[{host}]\x1b[0m {l}'
        else:
            fmt = '[{host}] {l}'
        msg = fmt.format(host=self.host, l=l)
        print(msg, file=sys.stderr)

Example 41

Project: chopsticks
Source File: ioloop.py
View license
    def println(self, l):
        if not PY2:
            l = l.decode('utf8')
        if sys.stderr.isatty():
            fmt = '\x1b[31m[{host}]\x1b[0m {l}'
        else:
            fmt = '[{host}] {l}'
        msg = fmt.format(host=self.host, l=l)
        print(msg, file=sys.stderr)

Example 42

Project: readerisdead
Source File: log.py
View license
def _stderr_supports_color():
    color = False
    if curses and sys.stderr.isatty():
        try:
            curses.setupterm()
            if curses.tigetnum("colors") > 0:
                color = True
        except Exception:
            pass
    return color

Example 43

Project: readerisdead
Source File: log.py
View license
def _stderr_supports_color():
    color = False
    if curses and sys.stderr.isatty():
        try:
            curses.setupterm()
            if curses.tigetnum("colors") > 0:
                color = True
        except Exception:
            pass
    return color

Example 44

Project: HoneyConnector
Source File: log.py
View license
def _stderr_supports_color():
    color = False
    if curses is not None and sys.stderr.isatty():
        try:
            curses.setupterm()
            if curses.tigetnum("colors") > 0:
                color = True
        except Exception:
            pass
    return color

Example 45

Project: HoneyConnector
Source File: log.py
View license
def _stderr_supports_color():
    color = False
    if curses is not None and sys.stderr.isatty():
        try:
            curses.setupterm()
            if curses.tigetnum("colors") > 0:
                color = True
        except Exception:
            pass
    return color

Example 46

Project: gdc-client
Source File: log.py
View license
def get_logger(name='gdc-client'):
    """Create or return an existing logger with given name
    """

    if name in loggers:
        return loggers[name]
    log = logging.getLogger(name)
    log.propagate = False
    if sys.stderr.isatty():
        formatter = LogFormatter()
    else:
        formatter = logging.Formatter('%(asctime)s: %(levelname)s: %(message)s')
    handler = logging.StreamHandler(sys.stderr)
    handler.setFormatter(formatter)
    log.addHandler(handler)
    loggers[name] = log
    return log

Example 47

Project: gdc-client
Source File: log.py
View license
def get_logger(name='gdc-client'):
    """Create or return an existing logger with given name
    """

    if name in loggers:
        return loggers[name]
    log = logging.getLogger(name)
    log.propagate = False
    if sys.stderr.isatty():
        formatter = LogFormatter()
    else:
        formatter = logging.Formatter('%(asctime)s: %(levelname)s: %(message)s')
    handler = logging.StreamHandler(sys.stderr)
    handler.setFormatter(formatter)
    log.addHandler(handler)
    loggers[name] = log
    return log

Example 48

Project: patient-viz
Source File: burst.py
View license
def flush_write_cache(delim, doQuote, write_cache, header):
    if sys.stderr.isatty():
        sys.stderr.write('\rflush cache')
    for outFile in write_cache.keys():
        lines = write_cache[outFile]
        if not os.path.isfile(outFile):
            with open(outFile, "w") as file:
                print(delim.join(map(doQuote, header)), file=file)
                for line in lines:
                    print(line, file=file)
        else:
            with open(outFile, "a") as file:
                for line in lines:
                    print(line, file=file)
    write_cache.clear()
    if sys.stderr.isatty():
        sys.stderr.write('\r           ')

Example 49

Project: chimera
Source File: output.py
View license
def xtermTitle(mystr):
    if havecolor and dotitles and "TERM" in os.environ and sys.stderr.isatty():
        myt = os.environ["TERM"]
        legal_terms = [
            "xterm", "Eterm", "aterm", "rxvt", "screen", "kterm", "rxvt-unicode"]
        for term in legal_terms:
            if myt.startswith(term):
                sys.stderr.write("\x1b]2;" + str(mystr) + "\x07")
                sys.stderr.flush()
                break

Example 50

Project: patient-viz
Source File: util.py
View license
def process_whitelisted_directory(dir, whitelist, cb, show_progress=True):
    wl = frozenset([ w[:3] for w in whitelist ]) if whitelist is not None else None
    dirty = False
    for (root, _, files) in sorted(os.walk(dir), key=itemgetter(0)):
        if root != dir:
            segs = root.split('/') # **/A/4/2/*.csv
            if len(segs) >= 4:
                segs = segs[-3:]
                if (
                        len(segs[0]) == 1 and
                        len(segs[1]) == 1 and
                        len(segs[2]) == 1
                    ):
                    if show_progress and sys.stderr.isatty():
                        try:
                            progr = (int(segs[0], 16)*16*16 + int(segs[1], 16)*16 + int(segs[2], 16)) / (16**3 - 1)
                            sys.stderr.write("processing: {0}/{1}/{2}/ {3:.2%}\r".format(segs[0], segs[1], segs[2], progr))
                            sys.stderr.flush()
                            dirty = True
                        except:
                            pass
                    if wl is None or "{0}{1}{2}".format(segs[0], segs[1], segs[2]) in wl:
                        for file in sorted(files):
                            if file.endswith(".csv"):
                                cb(os.path.join(root, file), False)
                    continue
        for file in sorted(files):
            if file.endswith(".csv"):
                if dirty and show_progress and sys.stderr.isatty():
                    print("", file=sys.stderr)
                    dirty = False
                cb(os.path.join(root, file), show_progress)
    if dirty and show_progress and sys.stderr.isatty():
        print("", file=sys.stderr)