Python curses.initscr() Examples

The following are 30 code examples of curses.initscr(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module curses , or try the search function .
Example #1
Source File: interface.py    From bitcoind-ncurses with MIT License 8 votes vote down vote up
def init_curses():
    window = curses.initscr()
    curses.noecho() # prevents user input from being echoed
    curses.curs_set(0) # make cursor invisible

    curses.start_color()
    curses.init_pair(1, curses.COLOR_GREEN, curses.COLOR_BLACK)
    curses.init_pair(2, curses.COLOR_CYAN, curses.COLOR_BLACK)
    curses.init_pair(3, curses.COLOR_RED, curses.COLOR_BLACK)
    curses.init_pair(4, curses.COLOR_MAGENTA, curses.COLOR_BLACK)
    curses.init_pair(5, curses.COLOR_YELLOW, curses.COLOR_BLACK)

    window.timeout(50)
    window.keypad(1) # interpret arrow keys, etc

    return window 
Example #2
Source File: CLI.py    From email_hack with MIT License 7 votes vote down vote up
def init_curses(self):
        """Setup the curses"""
        self.window = curses.initscr()
        self.height, self.width = self.window.getmaxyx()
        if self.width < 60:
            self.too_small = True
            return

        self.window.keypad(True)
        # self.window.nodelay(True)

        curses.noecho()
        curses.curs_set(False)
        curses.cbreak()
        curses.start_color()
        curses.init_pair(1, curses.COLOR_RED, curses.COLOR_BLACK)
        curses.init_pair(2, curses.COLOR_YELLOW, curses.COLOR_BLACK)
        curses.init_pair(3, curses.COLOR_WHITE, curses.COLOR_BLACK)
        curses.init_pair(4, curses.COLOR_GREEN, curses.COLOR_BLACK)
        curses.init_pair(5, curses.COLOR_WHITE, curses.COLOR_CYAN) 
Example #3
Source File: npyssafewrapper.py    From apple_bleee with GNU General Public License v3.0 6 votes vote down vote up
def wrapper_basic(call_function):
    #set the locale properly
    locale.setlocale(locale.LC_ALL, '')
    return curses.wrapper(call_function)

#def wrapper(call_function):
#   locale.setlocale(locale.LC_ALL, '')
#   screen = curses.initscr()
#   curses.noecho()
#   curses.cbreak()
#   
#   return_code = call_function(screen)
#   
#   curses.nocbreak()
#   curses.echo()
#   curses.endwin() 
Example #4
Source File: lcd_curses.py    From pydPiper with MIT License 6 votes vote down vote up
def __init__(self, rows=16, cols=100 ):

		self.FONTS_SUPPORTED = False

		self.rows = rows
		self.cols = cols

		self.stdscr = curses.initscr()
		self.curx = 0
		self.cury = 0

		if (curses.LINES < rows+1) or (curses.COLS < cols+1):
			raise RuntimeError(u"Screen too small.  Increase size to at least ({0}, {1})".format(rows+1, cols+1))

		# Set up parent class.  Note.  This must occur after display has been
		# initialized as the parent class may attempt to load custom fonts
		super(lcd_curses, self).__init__(rows,cols,1)

		locale.setlocale(locale.LC_ALL, '') 
Example #5
Source File: airpydump.py    From airpydump with MIT License 6 votes vote down vote up
def __init__(self, scanner):
		self.scanner = scanner
		self.screen = curses.initscr()
		curses.noecho()
		curses.cbreak()
		self.screen.keypad(1)
		self.screen.scrollok(True)
		self.x, self.y = self.screen.getmaxyx()
		curses.start_color()
		curses.use_default_colors()
		try:
			self.screen.curs_set(0)
		except:
			try:
				self.screen.curs_set(1)
			except:
				pass 
Example #6
Source File: __init__.py    From Fluid-Designer with GNU General Public License v3.0 6 votes vote down vote up
def initscr():
    import _curses, curses
    # we call setupterm() here because it raises an error
    # instead of calling exit() in error cases.
    setupterm(term=_os.environ.get("TERM", "unknown"),
              fd=_sys.__stdout__.fileno())
    stdscr = _curses.initscr()
    for key, value in _curses.__dict__.items():
        if key[0:4] == 'ACS_' or key in ('LINES', 'COLS'):
            setattr(curses, key, value)

    return stdscr

# This is a similar wrapper for start_color(), which adds the COLORS and
# COLOR_PAIRS variables which are only available after start_color() is
# called. 
Example #7
Source File: wrapper.py    From BinderFilter with MIT License 6 votes vote down vote up
def wrapper(func, *args, **kwds):
    """Wrapper function that initializes curses and calls another function,
    restoring normal keyboard/screen behavior on error.
    The callable object 'func' is then passed the main window 'stdscr'
    as its first argument, followed by any other arguments passed to
    wrapper().
    """

    try:
        # Initialize curses
        stdscr = curses.initscr()

        # Turn off echoing of keys, and enter cbreak mode,
        # where no buffering is performed on keyboard input
        curses.noecho()
        curses.cbreak()

        # In keypad mode, escape sequences for special keys
        # (like the cursor keys) will be interpreted and
        # a special value like curses.KEY_LEFT will be returned
        stdscr.keypad(1)

        # Start color, too.  Harmless if the terminal doesn't have
        # color; user can test with has_color() later on.  The try/catch
        # works around a minor bit of over-conscientiousness in the curses
        # module -- the error return from C start_color() is ignorable.
        try:
            curses.start_color()
        except:
            pass

        return func(stdscr, *args, **kwds)
    finally:
        # Set everything back to normal
        if 'stdscr' in locals():
            stdscr.keypad(0)
            curses.echo()
            curses.nocbreak()
            curses.endwin() 
Example #8
Source File: __init__.py    From oss-ftp with MIT License 6 votes vote down vote up
def initscr():
    import _curses, curses
    # we call setupterm() here because it raises an error
    # instead of calling exit() in error cases.
    setupterm(term=_os.environ.get("TERM", "unknown"),
              fd=_sys.__stdout__.fileno())
    stdscr = _curses.initscr()
    for key, value in _curses.__dict__.items():
        if key[0:4] == 'ACS_' or key in ('LINES', 'COLS'):
            setattr(curses, key, value)

    return stdscr

# This is a similar wrapper for start_color(), which adds the COLORS and
# COLOR_PAIRS variables which are only available after start_color() is
# called. 
Example #9
Source File: __init__.py    From Imogen with MIT License 6 votes vote down vote up
def initscr():
    import _curses, curses
    # we call setupterm() here because it raises an error
    # instead of calling exit() in error cases.
    setupterm(term=_os.environ.get("TERM", "unknown"),
              fd=_sys.__stdout__.fileno())
    stdscr = _curses.initscr()
    for key, value in _curses.__dict__.items():
        if key[0:4] == 'ACS_' or key in ('LINES', 'COLS'):
            setattr(curses, key, value)

    return stdscr

# This is a similar wrapper for start_color(), which adds the COLORS and
# COLOR_PAIRS variables which are only available after start_color() is
# called. 
Example #10
Source File: __init__.py    From ironpython3 with Apache License 2.0 6 votes vote down vote up
def initscr():
    import _curses, curses
    # we call setupterm() here because it raises an error
    # instead of calling exit() in error cases.
    setupterm(term=_os.environ.get("TERM", "unknown"),
              fd=_sys.__stdout__.fileno())
    stdscr = _curses.initscr()
    for key, value in _curses.__dict__.items():
        if key[0:4] == 'ACS_' or key in ('LINES', 'COLS'):
            setattr(curses, key, value)

    return stdscr

# This is a similar wrapper for start_color(), which adds the COLORS and
# COLOR_PAIRS variables which are only available after start_color() is
# called. 
Example #11
Source File: npyssafewrapper.py    From apple_bleee with GNU General Public License v3.0 6 votes vote down vote up
def wrapper_fork(call_function, reset=True):
    pid = os.fork()
    if pid:
        # Parent
        os.waitpid(pid, 0)
        if reset:
            external_reset()
    else:
        locale.setlocale(locale.LC_ALL, '')
        _SCREEN = curses.initscr()
        try:
            curses.start_color()
        except:
            pass
        _SCREEN.keypad(1)
        curses.noecho()
        curses.cbreak()
        curses.def_prog_mode()
        curses.reset_prog_mode()
        return_code = call_function(_SCREEN)
        _SCREEN.keypad(0)
        curses.echo()
        curses.nocbreak()
        curses.endwin()
        sys.exit(0) 
Example #12
Source File: ngxtop.py    From ngxtop with MIT License 6 votes vote down vote up
def setup_reporter(processor, arguments):
    if arguments['--no-follow']:
        return

    scr = curses.initscr()
    atexit.register(curses.endwin)

    def print_report(sig, frame):
        output = processor.report()
        scr.erase()
        try:
            scr.addstr(output)
        except curses.error:
            pass
        scr.refresh()

    signal.signal(signal.SIGALRM, print_report)
    interval = float(arguments['--interval'])
    signal.setitimer(signal.ITIMER_REAL, 0.1, interval) 
Example #13
Source File: colorlog.py    From pySINDy with MIT License 5 votes vote down vote up
def __init__(self, color=True, datefmt=None):
        r"""
        :arg bool color: Enables color support.
        :arg string fmt: Log message format.
        It will be applied to the attributes dict of log records. The
        text between ``%(color)s`` and ``%(end_color)s`` will be colored
        depending on the level if color support is on.
        :arg dict colors: color mappings from logging level to terminal color
        code
        :arg string datefmt: Datetime format.
        Used for formatting ``(asctime)`` placeholder in ``prefix_fmt``.
        .. versionchanged:: 3.2
        Added ``fmt`` and ``datefmt`` arguments.
        """
        logging.Formatter.__init__(self, datefmt=datefmt)
        self._colors = {}
        if color and _stderr_supports_color():
            # The curses module has some str/bytes confusion in
            # python3. Until version 3.2.3, most methods return
            # bytes, but only accept strings. In addition, we want to
            # output these strings with the logging module, which
            # works with unicode strings. The explicit calls to
            # unicode() below are harmless in python2 but will do the
            # right conversion in python 3.
            fg_color = (curses.tigetstr("setaf") or
                        curses.tigetstr("setf") or "")
            if (3, 0) < sys.version_info < (3, 2, 3):
                fg_color = str(fg_color, "ascii")

            for levelno, code in self.DEFAULT_COLORS.items():
                self._colors[levelno] = str(curses.tparm(fg_color, code), "ascii")
            self._normal = str(curses.tigetstr("sgr0"), "ascii")

            scr = curses.initscr()
            self.termwidth = scr.getmaxyx()[1]
            curses.endwin()
        else:
            self._normal = ''
            # Default width is usually 80, but too wide is worse than too narrow
            self.termwidth = 70 
Example #14
Source File: __init__.py    From ironpython3 with Apache License 2.0 5 votes vote down vote up
def wrapper(func, *args, **kwds):
    """Wrapper function that initializes curses and calls another function,
    restoring normal keyboard/screen behavior on error.
    The callable object 'func' is then passed the main window 'stdscr'
    as its first argument, followed by any other arguments passed to
    wrapper().
    """

    try:
        # Initialize curses
        stdscr = initscr()

        # Turn off echoing of keys, and enter cbreak mode,
        # where no buffering is performed on keyboard input
        noecho()
        cbreak()

        # In keypad mode, escape sequences for special keys
        # (like the cursor keys) will be interpreted and
        # a special value like curses.KEY_LEFT will be returned
        stdscr.keypad(1)

        # Start color, too.  Harmless if the terminal doesn't have
        # color; user can test with has_color() later on.  The try/catch
        # works around a minor bit of over-conscientiousness in the curses
        # module -- the error return from C start_color() is ignorable.
        try:
            start_color()
        except:
            pass

        return func(stdscr, *args, **kwds)
    finally:
        # Set everything back to normal
        if 'stdscr' in locals():
            stdscr.keypad(0)
            echo()
            nocbreak()
            endwin() 
Example #15
Source File: debug.py    From shadowlands with MIT License 5 votes vote down vote up
def end_debug():
    global debugging 

    stdscr = curses.initscr()
    curses.noecho()
    curses.cbreak()
    debugging = False 
Example #16
Source File: grid.py    From ngrid with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def show_model(model, cfg={}, num_frozen=0):
    """
    Shows an interactive view of the model on a connected TTY.

    @type model
      A model instance from this module.
    """
    full_cfg = dict(DEFAULT_CFG)
    full_cfg.update(cfg)
    cfg = full_cfg

    view = GridView(model, cfg, num_frozen=num_frozen)
    scr = curses.initscr()

    curses.start_color()
    curses.use_default_colors()
    curses.init_pair(1, -1, -1)                                     # normal
    curses.init_pair(2, curses.COLOR_BLUE, -1)                      # frozen
    curses.init_pair(3, -1, -1)                                     # separator
    curses.init_pair(4, -1, -1)                                     # footer
    curses.init_pair(5, curses.COLOR_BLACK, curses.COLOR_WHITE)     # cursor
    curses.init_pair(6, curses.COLOR_WHITE, curses.COLOR_BLUE)      # selection
    curses.init_pair(7, curses.COLOR_BLUE,  curses.COLOR_WHITE)     # frz sel

    try:
        curses.noecho()
        curses.cbreak()
        scr.keypad(1)
        view.set_screen(scr, locale.getpreferredencoding())
        view.show()
    finally:
        curses.nocbreak()
        scr.keypad(0)
        curses.echo()
        curses.endwin() 
Example #17
Source File: ncurses.py    From collection with MIT License 5 votes vote down vote up
def init (self):
		self.screen = curses.initscr()
		# curses.def_shell_mode()
		curses.noecho()
		curses.cbreak()
		self.screen.keypad(1)
		try:
			curses.start_color()
		except:
			pass
		return 0 
Example #18
Source File: raspcloud.py    From RaspberryCloud with GNU General Public License v3.0 5 votes vote down vote up
def init_curses():
    s = curses.initscr()
    curses.start_color()
    curses.use_default_colors()
    curses.noecho()
    s.scrollok(1)
    curses.curs_set(0)
    s.keypad(1)
    s.refresh()
    return s 
Example #19
Source File: graphics.py    From costar_plan with Apache License 2.0 5 votes vote down vote up
def __init__(self):
        self.stdscr = curses.initscr()
        curses.start_color()
        curses.init_pair(1, curses.COLOR_RED, curses.COLOR_BLACK)
        self.bottom_row = 0 
Example #20
Source File: cli.py    From wifibroadcast with GNU General Public License v3.0 5 votes vote down vote up
def main():
    stderr = sys.stderr

    if len(sys.argv) != 2:
        print("Usage: %s <profile>" % (sys.argv[0],), file=stderr)
        sys.exit(1)

    fd = tempfile.TemporaryFile()
    log.startLogging(fd)

    stdscr = curses.initscr()
    curses.noecho()
    curses.cbreak()
    curses.curs_set(0)
    stdscr.keypad(1)

    reactor.callWhenRunning(lambda: defer.maybeDeferred(init, stdscr, sys.argv[1])\
                            .addErrback(abort_on_crash))
    reactor.run()
    curses.endwin()
    rc = exit_status()

    if rc:
        log.msg('Exiting with code %d' % rc)
        fd.seek(0)
        for l in fd:
            stderr.write(l)

    sys.exit(rc) 
Example #21
Source File: evilmaid.py    From EvilAbigail with GNU General Public License v2.0 5 votes vote down vote up
def __init__(self):
        """
        Setup the main screen, progress bars and logging box
        """
        self.screen = curses.initscr()
        curses.curs_set(0)

        curses.start_color()
        curses.init_pair(1, curses.COLOR_RED, curses.COLOR_BLACK)
        curses.init_pair(2, curses.COLOR_GREEN, curses.COLOR_BLACK)
        curses.init_pair(3, curses.COLOR_MAGENTA, curses.COLOR_BLACK)
        curses.init_pair(4, curses.COLOR_CYAN, curses.COLOR_BLACK)
        curses.init_pair(5, curses.COLOR_BLUE, curses.COLOR_BLACK)
        curses.init_pair(6, curses.COLOR_YELLOW, curses.COLOR_BLACK)

        self.height, self.width = self.screen.getmaxyx()
        self.screen.border()

        self.preptotal()
        self.prepcurrent()
        self.preplog()
        self.banner()
        self.sig()

        self.drives = len(glob.glob("/dev/sd?1"))
        self.donedrives = 0
        self.prevprogress = 0
        self.loglines = []
        self.idx = 1 
Example #22
Source File: airpydump.py    From airpydump with MIT License 5 votes vote down vote up
def term_resize(self, sig, fr):
		curses.endwin()
		curses.initscr() 
Example #23
Source File: npyssafewrapper.py    From apple_bleee with GNU General Public License v3.0 5 votes vote down vote up
def wrapper_no_fork(call_function, reset=False):
    global _NEVER_RUN_INITSCR
    if not _NEVER_RUN_INITSCR:
        warnings.warn("""Repeated calls of endwin may cause a memory leak. Use wrapper_fork to avoid.""")
    global _SCREEN
    return_code = None
    if _NEVER_RUN_INITSCR:
        _NEVER_RUN_INITSCR = False
        locale.setlocale(locale.LC_ALL, '')
        _SCREEN = curses.initscr()
        try:
            curses.start_color()
        except:
            pass
        curses.noecho()
        curses.cbreak()
        _SCREEN.keypad(1)

    curses.noecho()
    curses.cbreak()
    _SCREEN.keypad(1)
    
    try:
        return_code = call_function(_SCREEN)    
    finally:
        _SCREEN.keypad(0)
        curses.echo()
        curses.nocbreak()
        # Calling endwin() and then refreshing seems to cause a memory leak.
        curses.endwin()
        if reset:
            external_reset()
    return return_code 
Example #24
Source File: sifter.py    From sandsifter with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def __init__(self, ts, injector, tests, do_tick, disassembler=disas_capstone):
        self.ts = ts;
        self.injector = injector
        self.T = tests
        self.gui_thread = None
        self.do_tick = do_tick
        self.ticks = 0

        self.last_ins_count = 0
        self.delta_log = deque(maxlen=self.RATE_Q)
        self.time_log = deque(maxlen=self.RATE_Q)

        self.disas = disassembler

        self.stdscr = curses.initscr()
        curses.start_color()

        # doesn't work
        # self.orig_colors = [curses.color_content(x) for x in xrange(256)]

        curses.use_default_colors()
        curses.noecho()
        curses.cbreak()
        curses.curs_set(0)
        self.stdscr.nodelay(1)

        self.sx = 0
        self.sy = 0

        self.init_colors()

        self.stdscr.bkgd(curses.color_pair(self.WHITE))

        self.last_time = time.time() 
Example #25
Source File: ui.py    From musicbox with MIT License 5 votes vote down vote up
def __init__(self):
        self.screen = curses.initscr()
        self.screen.timeout(100)  # the screen refresh every 100ms
        # charactor break buffer
        curses.cbreak()
        self.screen.keypad(1)

        curses.start_color()
        if Config().get("curses_transparency"):
            curses.use_default_colors()
            curses.init_pair(1, curses.COLOR_GREEN, -1)
            curses.init_pair(2, curses.COLOR_CYAN, -1)
            curses.init_pair(3, curses.COLOR_RED, -1)
            curses.init_pair(4, curses.COLOR_YELLOW, -1)
        else:
            curses.init_pair(1, curses.COLOR_GREEN, curses.COLOR_BLACK)
            curses.init_pair(2, curses.COLOR_CYAN, curses.COLOR_BLACK)
            curses.init_pair(3, curses.COLOR_RED, curses.COLOR_BLACK)
            curses.init_pair(4, curses.COLOR_YELLOW, curses.COLOR_BLACK)
        # term resize handling
        size = terminalsize.get_terminal_size()
        self.x = max(size[0], 10)
        self.y = max(size[1], 25)
        self.startcol = int(float(self.x) / 5)
        self.indented_startcol = max(self.startcol - 3, 0)
        self.update_space()
        self.lyric = ""
        self.now_lyric = ""
        self.post_lyric = ""
        self.now_lyric_index = 0
        self.tlyric = ""
        self.storage = Storage()
        self.config = Config()
        self.newversion = False 
Example #26
Source File: menu.py    From musicbox with MIT License 5 votes vote down vote up
def __init__(self):
        self.config = Config()
        self.datatype = "main"
        self.title = "网易云音乐"
        self.datalist = [
            "排行榜",
            "艺术家",
            "新碟上架",
            "精选歌单",
            "我的歌单",
            "主播电台",
            "每日推荐歌曲",
            "每日推荐歌单",
            "私人FM",
            "搜索",
            "帮助",
        ]
        self.offset = 0
        self.index = 0
        self.storage = Storage()
        self.storage.load()
        self.collection = self.storage.database["collections"]
        self.player = Player()
        self.player.playing_song_changed_callback = self.song_changed_callback
        self.cache = Cache()
        self.ui = Ui()
        self.api = NetEase()
        self.screen = curses.initscr()
        self.screen.keypad(1)
        self.step = 10
        self.stack = []
        self.djstack = []
        self.at_playing_list = False
        self.enter_flag = True
        signal.signal(signal.SIGWINCH, self.change_term)
        signal.signal(signal.SIGINT, self.send_kill)
        self.menu_starts = time.time()
        self.countdown_start = time.time()
        self.countdown = -1
        self.is_in_countdown = False 
Example #27
Source File: tui.py    From awesome-finder with MIT License 5 votes vote down vote up
def init_curses(self):
        """Setup the curses"""
        self.window = curses.initscr()
        self.window.keypad(True)

        curses.noecho()
        curses.cbreak()

        curses.start_color()
        curses.init_pair(1, curses.COLOR_CYAN, curses.COLOR_BLACK)
        curses.init_pair(2, curses.COLOR_BLACK, curses.COLOR_CYAN)

        self.current = curses.color_pair(2) 
Example #28
Source File: curses_ui.py    From deep_image_model with Apache License 2.0 5 votes vote down vote up
def _screen_init(self):
    """Screen initialization.

    Creates curses stdscr and initialize the color pairs for display.
    """

    self._stdscr = curses.initscr()
    self._command_window = None

    # Prepare color pairs.
    curses.start_color()

    self._color_pairs = {}
    color_index = 0

    for fg_color in self._FOREGROUND_COLORS:
      for bg_color in self._BACKGROUND_COLORS:

        color_index += 1
        curses.init_pair(color_index, self._FOREGROUND_COLORS[fg_color],
                         self._BACKGROUND_COLORS[bg_color])

        color_name = fg_color
        if bg_color != "black":
          color_name += "_on_" + bg_color

        self._color_pairs[color_name] = curses.color_pair(color_index)

    # A_BOLD is not really a "color". But place it here for convenience.
    self._color_pairs["bold"] = curses.A_BOLD

    # Default color pair to use when a specified color pair does not exist.
    self._default_color_pair = self._color_pairs["white"] 
Example #29
Source File: tui.py    From python-curses-scroll-example with MIT License 5 votes vote down vote up
def init_curses(self):
        """Setup the curses"""
        self.window = curses.initscr()
        self.window.keypad(True)

        curses.noecho()
        curses.cbreak()

        curses.start_color()
        curses.init_pair(1, curses.COLOR_CYAN, curses.COLOR_BLACK)
        curses.init_pair(2, curses.COLOR_BLACK, curses.COLOR_CYAN)

        self.current = curses.color_pair(2)

        self.height, self.width = self.window.getmaxyx() 
Example #30
Source File: cyberbot.py    From cyberbot with MIT License 5 votes vote down vote up
def init_scr(self):
        self.stdscr = curses.initscr()
        curses.noecho()
        curses.curs_set(0)

        self.stdscr_size = self.stdscr.getmaxyx()
        self.task_total = count_file_linenum(self.config.seedfile)

        self.pgsscr_size = (self.config.proc_num + 2, 40)
        self.pgsscr = curses.newpad(*self.pgsscr_size)
        self.cntscr_size = (4, 40)
        self.cntscr = curses.newpad(*self.cntscr_size)
        self.optscr_size = (18, 80)
        self.optscr = curses.newpad(*self.optscr_size)