Python curses 模块,endwin() 实例源码

我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用curses.endwin()

项目:HTP    作者:nklose    | 项目源码 | 文件源码
def __init__(self, file):
        self.file = file
        self.scr = curses.initscr()
        self.scr.border()
        self.scr_height, self.scr_width = self.scr.getmaxyx()
        self.text_win = curses.newwin(self.scr_height - 1, self.scr_width, 1, 0)
        self.file_text = file.content
        if self.file_text != None:
            self.text_win.addstr(self.file_text)
        curses.noecho()
        #curses.start_color()
        #curses.init_pair(1, curses.COLOR_BLACK, curses.COLOR_GREEN)

        if self.file.exists:
            self.start_editor()
        else:
            curses.endwin()
            gc.error('An error occurred while editing this file.')
项目:HTP    作者:nklose    | 项目源码 | 文件源码
def start_editor(self):
        try:
            # draw the top bar
            top_bar = 'Editing ' + self.file.name + ' [press Ctrl+G to save and close]'
            i = len(top_bar)
            while i < self.scr_width:
                top_bar += ' '
                i += 1
            self.scr.addstr(0, 0, top_bar, curses.A_REVERSE)
            self.scr.refresh()

            # let the user edit th efile
            box = Textbox(self.text_win)
            box.edit()

            # get the file contents
            self.file_text = box.gather()
        finally:
            # return to the game
            curses.endwin()
            gc.clear()
            self.file.content = self.file_text
项目:AutoCode    作者:HashCode55    | 项目源码 | 文件源码
def gmode(self):
        """
        Types automatically
        """
        try:
            fileptr = 0 
            while (fileptr + self.n) < len(self.file):                  
                text = self.get_text(fileptr)                    
                fileptr += self.n        
                self.stdscr.addstr(text)
                self.stdscr.refresh()
                sleep(0.1)  
            curses.endwin()                                                                                
        except KeyboardInterrupt:            
            curses.endwin()
            exit()
项目:paint-it    作者:plainspooky    | 项目源码 | 文件源码
def main():
    game = Game(16)

    while True:
        game.refresh_screen()
        new_color = game.get_key()
        if new_color > 0 and new_color <= COLORS and game.status!='win':
            old_color = game.arena[0][0]
            if new_color != old_color:
                game.moves+=1
                game.paint( [0,0], old_color, new_color)
        elif new_color==-2:
            break
        elif new_color==-1:
            game.display_help()

    game.screen.keypad(False)
    curses.nocbreak()
    curses.echo()
    curses.endwin()

    print('Thanks for playing!')
    exit()
项目:hakkuframework    作者:4shadoww    | 项目源码 | 文件源码
def main():
    try:
        screen = curses.initscr()
        size = screen.getmaxyx()
        sky = generateSky(size[0]-1, size[1]-1, 0.025)

        while True:
            if size[0] != screen.getmaxyx()[0] and size[1] != screen.getmaxyx()[1]:
                size = screen.getmaxyx()
                sky = generateSky(size[0]-1, size[1]-1, 0.05)

            animateSky(sky)
            renderSky(screen, sky)
            time.sleep(1)

        curses.endwin()

    except KeyboardInterrupt:
        curses.endwin()

    except:
        curses.endwin()
        traceback.print_exc()
项目:cyberbot    作者:RickGray    | 项目源码 | 文件源码
def run(self):
        while any(_.is_alive() for _ in self.processes):
            time.sleep(0.1)
            self.stdscr_size = self.stdscr.getmaxyx()
            self.build_progress_screen()
            self.build_status_screen()
            self.build_output_screen()

            # terminate manually when all tasks finished
            if self.task_num == self.task_total:
                for _ in self.processes:
                    _.terminate()

        self.stdscr.addstr(self.stdscr_size[0] - 2, 0,
                           'Done! please type "q" to exit.')
        self.stdscr.refresh()
        while self.stdscr.getch() != ord('q'):
            time.sleep(1)

        curses.endwin()
项目:pycreate2    作者:MomsFriendlyRobotCompany    | 项目源码 | 文件源码
def draw(self, opt):

        # Clear screen and draw default border:
        self.screen.clear()
        self.screen.border(0)
        self.screen.addstr(10, 30, 'Hello world!')  # Row 10, col 30
        self.screen.addstr(11, 30, '[q] Quit')  # Row 10, col 30
        # self.screen.addstr(12, 30, '[{} ] Forward'.format(u'\u21E7'.encode('utf-8')))  # Row 10, row 30
        # self.screen.addstr(20, 30, 'key {}'.format(opt))
        # self.screen.addstr(13, 30, '[{} ] Reverse'.format(u'\u21E9'.encode('utf-8')))
        # self.screen.addstr(14, 30, '[{} ] Left'.format(u'\u21E6'.encode('utf-8')))
        # self.screen.addstr(15, 30, '[{} ] Right'.format(u'\u21E8'.encode('utf-8')))

        self.screen.refresh()      # Redraw screen.

        # for key in self.windows:
        #   self.windows(key).refresh()
        self.windows['commands'].refresh()

        self.dummy += 0.1
        self.windows['light'].refresh([self.dummy,-2.2222,3333,-4444.44444])
        # win.refresh()
        # opt = screen.getch()  # Wait for user to enter character.
        # curses.endwin()       # End screen (ready to draw new one, but instead we exit)
        time.sleep(0.1)
项目:connect4    作者:guglielmilo    | 项目源码 | 文件源码
def init():
    height_term, width_term = get_terminal_size()
    height_min = COL_HEIGHT * HEIGHT + 2 + 9
    width_min = COL_WIDTH * WIDTH + 2 + 5
    if height_term < height_min or width_term < width_min:
        # resize the terminal to fit the minimum size to display the connect4 before exit
        stdout.write("\x1b[8;{h};{w}t".format(h=max(height_min, height_term), w=max(width_min, width_term)))
        exit('\033[91m' + 'The terminal was too small, you can now restart ' + '\033[1m' + 'Connect4' + '\033[0m')
    stdscr = curses.initscr()
    height,width = stdscr.getmaxyx()
    if height < height_min or width < width_min:
        # abort the program if the terminal can't be resized
        curses.endwin()
        exit('Please resize your terminal [%d%s%d] (minimum required %d%s%d)' %(width, 'x', height, width_min, 'x', height_min))
    curses.noecho()
    curses.cbreak()
    curses.curs_set(0)
    stdscr.keypad(1)
    #define the different colors
    if curses.can_change_color():
        defineColors()
    #return stdscr, width
    stdscr.clear()
    stdscr.border(0)
    return stdscr, width, height
项目:transmission_scripts    作者:leighmacdonald    | 项目源码 | 文件源码
def top(args):
    scr = curses.initscr()
    #scr.start_color()
    curses.noecho()
    curses.cbreak()
    hx, wm = scr.getmaxyx()
    scr.keypad(True)
    try:
        header = curses.newwin(HEADER_SIZE, wm, 0, 0)
        body = curses.newwin(BODY_SIZE, wm, HEADER_SIZE, 0)
        while True:
            draw_header(header)
            draw_body(body)
            draw_footer(scr)
            sleep(0.2)
    except KeyboardInterrupt:
        curses.nocbreak()
        scr.keypad(False)
        curses.echo()
        curses.endwin()
项目:gpymusic    作者:christopher-dG    | 项目源码 | 文件源码
def goodbye(self, msg=''):
        """
        Exit gpymusic.

        Arguements:
        msg='': Message to display prior to exiting.
        """
        if not self.curses:
            if not self.test:
                print(msg)
            sys.exit()

        self.addstr(self.outbar, msg)
        common.mc.logout()
        try:
            common.client.mm.logout()
        except:
            pass
        sleep(2)
        crs.curs_set(1)
        crs.endwin()
        sys.exit()
项目:LinuxBashShellScriptForOps    作者:DingGuodong    | 项目源码 | 文件源码
def refresh_window(procs, disks_read, disks_write):
    """Print results on screen by using curses."""
    curses.endwin()
    templ = "%-5s %-7s %11s %11s  %s"
    win.erase()

    disks_tot = "Total DISK READ: %s | Total DISK WRITE: %s" \
                % (bytes2human(disks_read), bytes2human(disks_write))
    print_line(disks_tot)

    header = templ % ("PID", "USER", "DISK READ", "DISK WRITE", "COMMAND")
    print_line(header, highlight=True)

    for p in procs:
        line = templ % (
            p.pid,
            p._username[:7],
            bytes2human(p._read_per_sec),
            bytes2human(p._write_per_sec),
            p._cmdline)
        try:
            print_line(line)
        except curses.error:
            break
    win.refresh()
项目:anonymine    作者:oskar-skog    | 项目源码 | 文件源码
def leave(self):
        '''Leave curses mode.'''
        curses.nocbreak()
        curses.echo()
        self.window.keypad(False)
        try:
            curses.curs_set(self.old_cursor)
        except:
            pass
        curses.endwin()
项目:AutoCode    作者:HashCode55    | 项目源码 | 文件源码
def __init__(self, file, n, godmode):
        """
        main is the wrapper window
        There are two nested windows, namely header and stdscr.        
        """
        self.main = curses.initscr()
        self.ROWS, self.COLS = self.main.getmaxyx()  

        self.header = self.main.subwin(2, self.COLS, 0, 0)
        # center the text 
        # cast it to int for python3 support
        center = int((self.COLS / 2) - (len(HEADER) / 2))
        self.header.addstr(center * ' ' + HEADER)        
        self.header.refresh()

        self.stdscr = self.main.subwin(self.ROWS-1, self.COLS, 1, 0)        
        self.stdscr.idlok(True) 
        self.stdscr.scrollok(True)  

        curses.cbreak()        
        curses.noecho()         

        self.stdscr.keypad(1)
        self.stdscr.refresh()

        self.file = file           
        # this is for handling the backspaces 
        self.virtualfile = file.split('\n') 

        self.godmode = godmode
        self.n = n   

        # handle terminal size
        if self.COLS < 100:
            curses.endwin()            
            print ('Error: Increase the width of your terminal')
            sys.exit(1)
项目:supremm    作者:ubccr    | 项目源码 | 文件源码
def __exit__(self, exc_type, exc_value, traceback):
        """ reset terminal settings and de-init curses """
        self.stdscr.keypad(0)
        curses.nocbreak()
        curses.echo()
        curses.endwin()
项目:notex    作者:adiultra    | 项目源码 | 文件源码
def close(self):
        self.text = self.text_orig
        curses.endwin()
        curses.flushinp()
        return False
项目:Round1    作者:general-ai-challenge    | 项目源码 | 文件源码
def finalize(self):
        curses.nocbreak()
        curses.echo()
        curses.endwin()
项目:I2C-LCD-Display    作者:bradgillap    | 项目源码 | 文件源码
def cleanup():
   curses.nocbreak()
   curses.echo()
   curses.endwin()
   pi.stop()
项目:botany    作者:jifunks    | 项目源码 | 文件源码
def __exit__(self):
        self.exit = True
        curses.curs_set(2)
        curses.endwin()
        os.system('clear')
项目:hostapd-mana    作者:adde88    | 项目源码 | 文件源码
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()
项目:awesome-finder    作者:mingrammer    | 项目源码 | 文件源码
def run(self):
        """Continue running the awesome finder until interrupted"""
        try:
            self.input_stream()
        except KeyboardInterrupt:
            pass
        finally:
            curses.endwin()
项目:getTimer    作者:maxwellgerber    | 项目源码 | 文件源码
def _stopWindow(stdscr):
    stdscr.erase()
    stdscr.refresh()
    stdscr.keypad(0)
    curses.echo()
    curses.curs_set(1)
    curses.nocbreak()
    curses.endwin()
项目:getTimer    作者:maxwellgerber    | 项目源码 | 文件源码
def _cleanup():
    curses.echo()
    curses.curs_set(1)
    curses.nocbreak()
    curses.endwin()
    traceback.print_exc()
项目:captiv8    作者:wraith-wireless    | 项目源码 | 文件源码
def teardown(win):
    """
     returns console to normal state
     :param win: the window
    """
    # tear down the console
    curses.nocbreak()
    if win: win.keypad(0)
    curses.echo()
    curses.endwin()
项目:pyfeld    作者:scjurgen    | 项目源码 | 文件源码
def __exit__(self, exc_type, exc_val, exc_tb):
        self.window.keypad(0)
        curses.echo()
        curses.nocbreak()
        curses.endwin()
项目:pyfeld    作者:scjurgen    | 项目源码 | 文件源码
def run_main_loop(self):
        self.draw_ui()
        self.window.move(1, 1)
        while 1:
            c = self.window.getch()
            if curses.keyname(c) in [b'q', b'Q']:
                break
            elif c == 27:
                break
            elif curses.keyname(c) in [b'i', b'I']:
                break
            self.show_notification_state(uuid_store)
        curses.endwin()
项目:pyfeld    作者:scjurgen    | 项目源码 | 文件源码
def __exit__(self, exc_type, exc_val, exc_tb):
        self.window.keypad(0)
        curses.echo()
        curses.nocbreak()
        curses.endwin()
项目:sandsifter    作者:xoreaxeaxeax    | 项目源码 | 文件源码
def cleanup(gui, poll, injector, ts, tests, command_line, args):
    ts.run = False
    if gui:
        gui.stop()
    if poll:
        poll.stop()
    if injector:
        injector.stop()

    '''
    # doesn't work
    if gui:
        for (i, c) in enumerate(gui.orig_colors):
            curses.init_color(i, c[0], c[1], c[2])
    '''

    curses.nocbreak();
    curses.echo()
    curses.endwin()

    dump_artifacts(tests, injector, command_line)

    if args.save:
        with open(LAST, "w") as f:
            f.write(hexlify(cstr2py(tests.r.raw_insn)))

    sys.exit(0)
项目:sandsifter    作者:xoreaxeaxeax    | 项目源码 | 文件源码
def stop(self):
        curses.nocbreak();
        curses.echo()
        curses.endwin()
项目:mitogen    作者:dw    | 项目源码 | 文件源码
def close(self):
        curses.endwin()
项目:hakkuframework    作者:4shadoww    | 项目源码 | 文件源码
def matrix(self, args):
        try:
            core.matrix.main()
        except KeyboardInterrupt:
            curses.endwin()
            curses.curs_set(1)
            curses.reset_shell_mode()
            curses.echo()
项目:huhamhire-hosts    作者:jiangsile    | 项目源码 | 文件源码
def __del__(self):
        """
        Reset terminal before quit.
        """
        curses.nocbreak()
        curses.echo()
        curses.endwin()
项目:cursed    作者:johannestaas    | 项目源码 | 文件源码
def run(self):
        '''
        Runs all the windows added to the application, and returns a `Result`
        object.

        '''
        result = Result()
        try:
            self.scr = curses.initscr()
            self.MAX_HEIGHT, self.MAX_WIDTH = self.scr.getmaxyx()
            curses.noecho()
            curses.cbreak()
            curses.start_color()
            curses.use_default_colors()
            self.window = self.scr.subwin(0, 0)
            self.window.keypad(1)
            self.window.nodelay(1)
            self._run_windows()
            self.threads += [gevent.spawn(self._input_loop)]
            gevent.joinall(self.threads)
            for thread in self.threads:
                if thread.exception:
                    result._extract_thread_exception(thread)
        except KeyboardInterrupt:
            result._extract_exception()
        except Exception:
            result._extract_exception()
        finally:
            if self.scr is not None:
                self.scr.keypad(0)
                curses.echo()
                curses.nocbreak()
                curses.endwin()
        return result
项目:Remixatron    作者:drensin    | 项目源码 | 文件源码
def cleanup():
    """Cleanup before exiting"""

    if not window:
        return

    w_str = get_window_contents()
    curses.curs_set(1)
    curses.endwin()

    print w_str.rstrip()
    print

    mixer.quit()
项目:zippy    作者:securesystemslab    | 项目源码 | 文件源码
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()
项目:pycreate2    作者:MomsFriendlyRobotCompany    | 项目源码 | 文件源码
def __del__(self):
        curses.nocbreak()
        curses.echo()
        curses.endwin()
        # print('done')
项目:gintonic    作者:redahe    | 项目源码 | 文件源码
def close_curses():
    mainwindow.keypad(0)
    curses.echo()
    curses.nocbreak()
    curses.curs_set(2)
    curses.endwin()
项目:AsciiDots-Java    作者:LousyLynx    | 项目源码 | 文件源码
def on_finish(self):
        global interpreter

        if self.debug and not self.compat_debug:
            curses.nocbreak()
            self.stdscr.keypad(False)
            curses.echo()

            curses.endwin()

        # sys.exit(0)
项目:sawtooth-validator    作者:hyperledger-archives    | 项目源码 | 文件源码
def run_stats(url,
              stats_update_frequency=3,
              endpoint_update_frequency=30,
              csv_enable_summary=False,
              csv_enable_validator=False
              ):
    try:
        # initialize globals when we are read for stats display. This keeps
        # curses from messing up the status prints prior to stats start up.
        epm = EndpointManager()
        sm = StatsManager()  # sm assumes epm is created!

        # initialize csv stats file generation
        print "initializing csv"
        sm.csv_init(csv_enable_summary, csv_enable_validator)

        # prevent curses import from modifying normal terminal operation
        # (suppression of cr-lf) during display of help screen, config settings
        if curses_imported:
            curses.endwin()

        # discover validator endpoints; if successful, continue with startup()
        epm.initialize_endpoint_discovery(
            url,
            startup,
            {
                'loop_times': {
                    "stats": stats_update_frequency,
                    'endpoint': endpoint_update_frequency},
                'stats_man': sm,
                'ep_man': epm
            })

        reactor.run()

        sm.stats_stop()
    except Exception as e:
        if curses_imported:
            curses.endwin()
        sys.stderr.write(e)
        raise
项目:sawtooth-validator    作者:hyperledger-archives    | 项目源码 | 文件源码
def cpstop(self):
        if self.use_curses:
            curses.nocbreak()
            self.scrn.keypad(0)
            curses.echo()
            curses.endwin()
项目:WxNeteaseMusic    作者:yaphone    | 项目源码 | 文件源码
def send_kill(self, signum, fram):
        self.player.stop()
        self.cache.quit()
        self.storage.save()
        curses.endwin()
        sys.exit()
项目:camTerm    作者:andy1729    | 项目源码 | 文件源码
def signal_handler(signal, frame):
    print 'You pressed Ctrl + C!'
    curses.endwin()
    sys.exit(0)
项目:oil    作者:oilshell    | 项目源码 | 文件源码
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()
项目:sciibo    作者:fdev    | 项目源码 | 文件源码
def create_screen(fn):
    """
    Initializes curses and passes a Screen to the main loop function `fn`.
    Based on curses.wrapper.
    """
    try:
        # Make escape key more responsive
        os.environ['ESCDELAY'] = '25'

        stdscr = curses.initscr()

        curses.noecho()
        curses.cbreak()
        stdscr.keypad(1)
        stdscr.nodelay(1)
        curses.curs_set(0)

        curses.mousemask(curses.BUTTON1_CLICKED)

        if curses.has_colors():
            curses.start_color()
            curses.use_default_colors()

        screen = Screen(stdscr)
        fn(screen)

    finally:
        # Set everything back to normal
        if 'stdscr' in locals():
            curses.use_default_colors()
            curses.curs_set(1)
            stdscr.keypad(0)
            curses.echo()
            curses.nocbreak()
            curses.endwin()
项目:python2-tracer    作者:extremecoders-re    | 项目源码 | 文件源码
def main():
    if not sys.argv[1:]:
        print __doc__
        sys.exit(0)
    cmd = " ".join(sys.argv[1:])
    p = os.popen(cmd, "r")
    text = p.read()
    sts = p.close()
    if sts:
        print >>sys.stderr, "Exit code:", sts
        sys.exit(sts)
    w = curses.initscr()
    try:
        while True:
            w.erase()
            try:
                w.addstr(text)
            except curses.error:
                pass
            w.refresh()
            time.sleep(1)
            p = os.popen(cmd, "r")
            text = p.read()
            sts = p.close()
            if sts:
                print >>sys.stderr, "Exit code:", sts
                sys.exit(sts)
    finally:
        curses.endwin()
项目:python2-tracer    作者:extremecoders-re    | 项目源码 | 文件源码
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()
项目:autoinjection    作者:ChengWiLL    | 项目源码 | 文件源码
def getConsoleWidth(default=80):
    """
    Returns console width
    """

    width = None

    if os.getenv("COLUMNS", "").isdigit():
        width = int(os.getenv("COLUMNS"))
    else:
        try:
            try:
                FNULL = open(os.devnull, 'w')
            except IOError:
                FNULL = None
            process = subprocess.Popen("stty size", shell=True, stdout=subprocess.PIPE, stderr=FNULL or subprocess.PIPE)
            stdout, _ = process.communicate()
            items = stdout.split()

            if len(items) == 2 and items[1].isdigit():
                width = int(items[1])
        except (OSError, MemoryError):
            pass

    if width is None:
        try:
            import curses

            stdscr = curses.initscr()
            _, width = stdscr.getmaxyx()
            curses.endwin()
        except:
            pass

    return width or default
项目:cursebox    作者:Tenchi2xh    | 项目源码 | 文件源码
def __exit__(self, exc_type, exc_val, exc_tb):
        # for thread in self.threads:
        #     thread.join()
        curses.noraw()
        self.screen.keypad(False)
        curses.echo()
        curses.endwin()
项目:Tadman    作者:KeepPositive    | 项目源码 | 文件源码
def main_loop(a_dict, inst_dict, name, version, build_type):

    """ This is a simple function with the goal of making scripts that
    utilize this interface more clean. It sets all of the vital info,
    and runs all of the major loops available in a specific order.
    """

    interface = MainInterface(a_dict, inst_dict)

    interface.package_name = name
    interface.package_version = version
    interface.build_type = build_type

    interface.init_package_info_entry()

    exit_main = False

    while not exit_main:
        if interface.window == 'build':
            exit_main, build_package = interface.run_option_loop()
        elif interface.window == 'install':
            exit_main, build_package = interface.run_install_loop()
        elif interface.window == 'build-help':
            exit_main, build_package = interface.run_help_loop('build')
        elif interface.window == 'install-help':
            exit_main, build_package = interface.run_help_loop('install')

    curses.endwin()

    if build_package:
        return interface.get_return_values()
    else:
        return False
项目:gdax-trader    作者:mcardillo55    | 项目源码 | 文件源码
def close(self):
        if not self.enable:
            return
        curses.nocbreak()
        self.stdscr.keypad(0)
        curses.echo()
        curses.endwin()
项目:wpm    作者:cslarsen    | 项目源码 | 文件源码
def deinit(self):
        curses.nocbreak()
        self.screen.keypad(False)
        curses.echo()
        curses.endwin()