예제 #1
0
파일: ui.py 프로젝트: Zorgodon/musicbox
    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)
        self.netease = NetEase()

        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_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.tlyric = ''
        self.storage = Storage()
        self.config = Config()
        self.newversion = False
예제 #2
0
def print_game_field():
    '''
    Function prints game field.
    Arguments: none
    Return: 
        game_matrix - array with screen coordinates
    '''
    cols, rows = terminalsize.get_terminal_size()
    start_x = cols/2-5
    start_y = rows/2-5
    sys.stdout.write("\033[{}H".format(start_y))
    sys.stdout.write("\033[{}G   |   |   \n".format(start_x))
    sys.stdout.write("\033[{}G---+---+---\n".format(start_x))
    sys.stdout.write("\033[{}G   |   |   \n".format(start_x))
    sys.stdout.write("\033[{}G---+---+---\n".format(start_x))
    sys.stdout.write("\033[{}G   |   |   \n".format(start_x))
    sys.stdout.flush()
    
    game_matrix = []
    for x in range(3):
        game_matrix.append([])
        for y in range(3):
            game_matrix[x].append({'x':(start_x+1+x*4),'y':(start_y+y*2)})
    
    return game_matrix
예제 #3
0
파일: ui.py 프로젝트: royaso/musicbox
    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)
        self.netease = NetEase()

        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_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.storage = Storage()
        self.newversion = False

        # Set cursor to invisible.
        try:
            curses.curs_set(0)
        except curses.error:
            # The terminal does not supports the visibility requested.
            pass
예제 #4
0
파일: main.py 프로젝트: mhspradlin/python
def main():
    print("Let the adventure begin!")
    getgoing()
    print("And so we continue!")
    #Give the screen dimensions greater scope than the renderscreen function
    (widthpass, heightpass) = terminalsize.get_terminal_size()
    #The first screen
    (numofchoices, choicemap) = renderscreen("_init", widthpass, heightpass)
    #The main game loop
    while True == True:
        #getchoice handles exiting the loop, so no external control is needed
        choice = getchoice(numofchoices)
        #Get the proper screen size
        (widthpass, heightpass) = terminalsize.get_terminal_size()
        #Will use the choice to render the appropriate screen, ultimately
        (numofchoices, choicemap) = renderscreen(choicemap[choice], widthpass, heightpass)
예제 #5
0
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
예제 #6
0
def borrar(secadora):
	global esclavo
	width,height=terminalsize.get_terminal_size()
	sys.stdout.write('\0\033[' + str(esclavo[secadora].renglon) + ';1H')
	sys.stdout.write('\0\033[1;31m')
	printw(esclavo[secadora].nombre)
	printw('-',width-9)
예제 #7
0
def print_game_field():
    '''
    Function prints game field.
    Arguments: none
    Return: 
        game_matrix - array with screen coordinates
    '''
    cols, rows = terminalsize.get_terminal_size()
    start_x = cols / 2 - 5
    start_y = rows / 2 - 5
    sys.stdout.write("\033[{}H".format(start_y))
    sys.stdout.write("\033[{}G   |   |   \n".format(start_x))
    sys.stdout.write("\033[{}G---+---+---\n".format(start_x))
    sys.stdout.write("\033[{}G   |   |   \n".format(start_x))
    sys.stdout.write("\033[{}G---+---+---\n".format(start_x))
    sys.stdout.write("\033[{}G   |   |   \n".format(start_x))
    sys.stdout.flush()

    game_matrix = []
    for x in range(3):
        game_matrix.append([])
        for y in range(3):
            game_matrix[x].append({
                'x': (start_x + 1 + x * 4),
                'y': (start_y + y * 2)
            })

    return game_matrix
예제 #8
0
    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)
        self.netease = NetEase()

        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_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.tlyric = ''
        self.storage = Storage()
        self.config = Config()
        self.newversion = False
예제 #9
0
def clearLine():
    '''
    Clears the current line, then \r. 
    Used when previously printed without \n. 
    '''
    terminal_width = get_terminal_size()[0] - 1
    print('\r', ' ' * terminal_width, end='\r', sep='')
예제 #10
0
파일: dsr.py 프로젝트: dkratzert/DSR
 def list_dbentries(self):
     """
     list all entries in the db.
     """
     dbdir = os.path.expanduser('~')
     fragnames = []
     num = 0
     try:
         (width, _) = get_terminal_size()
     except():
         width = 80
     print('\n Entries found in the databases:\n')
     print(' Fragment         | Line | DB Name    | Full name, Comments ')
     print(sep_line)
     for num, line in enumerate(self.gdb.list_fragments()):
         fragnames.append(line[0])
         line = ' {:<17}| {:<5}| {:<11}| {}'.format(*line)
         print(line[:width - 1])
     print('\n {} Fragments in the database(s).'.format(num),
           '\n Feel free to add more fragments to "{}dsr_user_db.txt"'.format(dbdir + os.path.sep))
     for fragment in fragnames:
         self.gdb.check_consistency(fragment)
         self.gdb.check_db_atom_consistency(fragment)
         self.gdb.check_db_restraints_consistency(fragment)
         self.gdb.check_sadi_consistence(fragment)
     from selfupdate import is_update_needed
     if is_update_needed(silent=True):
         print("\n*** An update for DSR is available. You can update with 'dsr -u' ***")
     sys.exit()
    def _reportDownload(self, blocksDownload, blockSize, fileSize):
        'Print progress of the actual download'
        sizeDownloaded = int(blockSize * blocksDownload / 1024)
        totalSize = int(fileSize / 1024)
        percentDown = 0.0

        if sizeDownloaded != 0:
            percentDown = sizeDownloaded / totalSize

        term_width = terminalsize.get_terminal_size()[0]

        if not sizeDownloaded < totalSize:
            sizeDownloaded = totalSize

        leftMsg = (self.fileName + '  [')
        rightMsg = '] ' + str(sizeDownloaded) + ' / ' + str(totalSize) + ' KB'
        leftSize = len(leftMsg)
        consoleSpace = term_width - (
            leftSize + 20
        )  # plus 16 to have a reserve from end with right message for showing size
        showNumSharps = int(consoleSpace * percentDown)

        print(leftMsg.ljust(showNumSharps + leftSize,
                            '#').ljust(consoleSpace + leftSize) + rightMsg,
              end='\r')

        if not sizeDownloaded < totalSize:
            print('')
예제 #12
0
def main():
    assert_git_config()

    try:
        usage = ("""usage: %prog <command> [options]
       %prog clone [-r alias] [-m URL]
       %prog branch [-r alias] [-m URL] [--rf package] [--dryrun]
       %prog prepare [-r alias] [-m URL] [--rf package] [--dryrun]
       %prog perform [-r alias] [-m URL] [--rf package] [--dryrun]""")
        description = """Release Nuxeo Packages.\n
The first call must provide an URL for the configuration. If set to '' (empty string), it defaults to '%s'. You can use
a local file URL ('file://').\n
Then, a 'release.ini' file is generated and will be reused for the next calls. For each package, a
'release-$PACKAGE_NAME.log' file is also generated and corresponds to the file generated by the release.py script.\n
The 'release.ini' file contains informations about the release process:\n
- 'prepared = True' if the prepare task succeeded,\n
- 'performed = True' if the perform task succeeded,\n
- 'uploaded = ...' if an upload successfully happened,\n
- 'skip = Failed!' followed by a stack trace in case of error.\n
The script can be re-called: it will skip the packages with a skip value and skip the prepare (or perform) if
'prepared = True' (or 'performed = True').\n
Failed uploads are not retried and must be manually done.""" % DEFAULT_MP_CONF_URL
        help_formatter = IndentedHelpFormatterWithNL(max_help_position=7, width=get_terminal_size()[0])
        parser = optparse.OptionParser(usage=usage, description=description, formatter=help_formatter)
        parser.add_option('-r', action="store", type="string", dest='remote_alias', default='origin',
                          help="""The Git alias of remote URL. Default: '%default'""")
        parser.add_option('-m', "--marketplace-conf", action="store", type="string", dest='marketplace_conf',
                          default=None, help="""The Marketplace configuration URL. Default: '%default'""")
        parser.add_option('-i', '--interactive', action="store_true", dest='interactive', default=False,
                          help="""Not implemented (TODO NXP-8573). Interactive mode. Default: '%default'""")
        parser.add_option('--rf', '--restart-from', action="store", dest='restart_from', default=None,
                          help="""Restart from a package. Default: '%default'""")
        parser.add_option('--dryrun', action="store_true", dest='dryrun', default=False,
                          help="""Dry run mode. Default: '%default'""")
        (options, args) = parser.parse_args()
        if len(args) == 1:
            command = args[0]
        elif len(args) > 1:
            raise ExitException(1, "'command' must be a single argument. See usage with '-h'.")
        full_release = ReleaseMP(options.remote_alias, options.restart_from, options.marketplace_conf)
        if "command" not in locals():
            raise ExitException(1, "Missing command. See usage with '-h'.")
        elif command == "clone":
            full_release.clone()
        elif command == "branch":
            full_release.release_branch(dryrun=options.dryrun)
        elif command == "prepare":
            full_release.prepare(dryrun=options.dryrun)
        elif command == "perform":
            full_release.perform(dryrun=options.dryrun)
        elif command == "test":
            full_release.test()
        else:
            raise ExitException(1, "Unknown command! See usage with '-h'.")
    except ExitException, e:
        if e.message is not None:
            log("[ERROR] %s" % e.message, sys.stderr)
        sys.exit(e.return_code)
예제 #13
0
파일: release_mp.py 프로젝트: Vozro/nuxeo
def main():
    assert_git_config()

    try:
        usage = ("""usage: %prog <command> [options]
       %prog clone [-r alias] [-m URL]
       %prog branch [-r alias] [-m URL] [--rf package] [--dryrun]
       %prog prepare [-r alias] [-m URL] [--rf package] [--dryrun]
       %prog perform [-r alias] [-m URL] [--rf package] [--dryrun]""")
        description = """Release Nuxeo Packages.\n
The first call must provide an URL for the configuration. If set to '' (empty string), it defaults to '%s'. You can use
a local file URL ('file://').\n
Then, a 'release.ini' file is generated and will be reused for the next calls. For each package, a
'release-$PACKAGE_NAME.log' file is also generated and corresponds to the file generated by the release.py script.\n
The 'release.ini' file contains informations about the release process:\n
- 'prepared = True' if the prepare task succeeded,\n
- 'performed = True' if the perform task succeeded,\n
- 'uploaded = ...' if an upload successfully happened,\n
- 'skip = Failed!' followed by a stack trace in case of error.\n
The script can be re-called: it will skip the packages with a skip value and skip the prepare (or perform) if
'prepared = True' (or 'performed = True').\n
Failed uploads are not retried and must be manually done.""" % DEFAULT_MP_CONF_URL
        help_formatter = IndentedHelpFormatterWithNL(max_help_position=7, width=get_terminal_size()[0])
        parser = optparse.OptionParser(usage=usage, description=description, formatter=help_formatter)
        parser.add_option('-r', action="store", type="string", dest='remote_alias', default='origin',
                          help="""The Git alias of remote URL. Default: '%default'""")
        parser.add_option('-m', "--marketplace-conf", action="store", type="string", dest='marketplace_conf',
                          default=None, help="""The Marketplace configuration URL. Default: '%default'""")
        parser.add_option('-i', '--interactive', action="store_true", dest='interactive', default=False,
                          help="""Not implemented (TODO NXP-8573). Interactive mode. Default: '%default'""")
        parser.add_option('--rf', '--restart-from', action="store", dest='restart_from', default=None,
                          help="""Restart from a package. Default: '%default'""")
        parser.add_option('--dryrun', action="store_true", dest='dryrun', default=False,
                          help="""Dry run mode. Default: '%default'""")
        (options, args) = parser.parse_args()
        if len(args) == 1:
            command = args[0]
        elif len(args) > 1:
            raise ExitException(1, "'command' must be a single argument. See usage with '-h'.")
        full_release = ReleaseMP(options.remote_alias, options.restart_from, options.marketplace_conf)
        if "command" not in locals():
            raise ExitException(1, "Missing command. See usage with '-h'.")
        elif command == "clone":
            full_release.clone()
        elif command == "branch":
            full_release.release_branch(dryrun=options.dryrun)
        elif command == "prepare":
            full_release.prepare(dryrun=options.dryrun)
        elif command == "perform":
            full_release.perform(dryrun=options.dryrun)
        elif command == "test":
            full_release.test()
        else:
            raise ExitException(1, "Unknown command! See usage with '-h'.")
    except ExitException, e:
        if e.message is not None:
            log("[ERROR] %s" % e.message, sys.stderr)
        sys.exit(e.return_code)
예제 #14
0
    def __init__(self, printable, frame_rate=10):
        Thread.__init__(self)
        self.printable = printable
        self.frame_rate = frame_rate
        self.terminal_width, _ = get_terminal_size()

        self.stop = False
        self.setDaemon(True)
        self.start()
예제 #15
0
def get_width():
    dimensions = get_terminal_size()
    global wrap_width
    if (dimensions[0] >= 20):
        wrap_width = dimensions[
            0] - 5  # Get the width of the user's window so we can wrap text.
    else:
        wrap_width = dimensions[0]
    return dimensions
예제 #16
0
 def _update_char_length(self):
     if len(self.bars) == 0:
         return
     terminal_width, _ = get_terminal_size()
     separator_length = len(self.bars) - 1 if len(self.bars) >= 2 else 0
     available_width = terminal_width - len(
         self.prefix +
         self.suffix) - self.percent_decimal - 10 - separator_length
     self.char_length = available_width // len(self.bars)
예제 #17
0
def print_top_right(text):
    '''
    print text to top right in terminal
    '''
    (width, heigth) = terminalsize.get_terminal_size()  # @UnusedVariable
    text_len = len(text)
    text = '| %s |' % text
    print_there(1, width - len(text) + 1, '+%s+' % ('-' * (text_len + 2)))
    print_there(2, width - len(text) + 1, text)
    print_there(3, width - len(text) + 1, '+%s+' % ('-' * (text_len + 2)))
예제 #18
0
    def _setConsoleDimensions(self):

        term_size = get_terminal_size()

        # Grab current console dimensions
        self._height = term_size[1]
        self._width = term_size[0]

        # Always save a spot for the input at the bottom
        self._height -= 1
예제 #19
0
 def Draw(self, state=None):
     if state == None and self.state != None:
         for i in range(self.dim.H):
             if self.align == CENTER:
                 for j in range(
                     (get_terminal_size()[0] // 2 - self.dim.W) // 2):
                     print('  ', end='')
             elif self.align == RIGHT:
                 for j in range(get_terminal_size()[0] // 2 - self.dim.W):
                     print('  ', end='')
             for j in range(self.dim.W):
                 col = self.grid[self.state].Get(j, i)
                 if col != 'black':
                     cprint('  ',
                            col,
                            'on_' + self.grid[self.state].Get(j, i),
                            end='')
                 else:
                     print('  ', end='')
             print('')
     elif state != None:
         for i in range(self.dim.H):
             if self.align == CENTER:
                 for j in range(
                     (get_terminal_size()[0] // 2 - self.dim.W) // 2):
                     print('  ', end='')
             elif self.align == RIGHT:
                 for j in range(get_terminal_size()[0] // 2 - self.dim.W):
                     print('  ', end='')
             for j in range(self.dim.W):
                 col = self.grid[state].Get(j, i)
                 if col != 'black':
                     cprint('  ',
                            col,
                            'on_' + self.grid[state].Get(j, i),
                            end='')
                 else:
                     print('  ', end='')
             print('')
     else:
         raise ValueError(
             'Must specify \'state\' parameter if \'SetState()\' had not been invoked before.'
         )
예제 #20
0
 def __init__(self, w, h, align=LEFT):
     cols, rows = get_terminal_size()
     if w * 2 > cols or h + 1 > rows:
         raise ValueError(
             'The given width and height are too big. Please resize your terminal or stick to these dimensions: {}x{}.'
             .format(cols // 2, rows + 1))
     self.dim = Rectangle(0, 0, w, h)
     self.align = align
     self.grid = {}
     self.state = None
예제 #21
0
def execute(workload_result_file, command_lines):
    proc = subprocess.Popen(" ".join(command_lines),
                            shell=True,
                            bufsize=1,
                            stdout=subprocess.PIPE,
                            stderr=subprocess.STDOUT)
    count = 100
    last_time = 0
    log_file = open(workload_result_file, 'w')
    # see http://stackoverflow.com/a/4417735/1442961
    lines_iterator = iter(proc.stdout.readline, b"")
    for line in lines_iterator:
        count += 1
        if count > 100 or time(
        ) - last_time > 1:  # refresh terminal size for 100 lines or each seconds
            count, last_time = 0, time()
            width, height = get_terminal_size()
            width -= 1

        try:
            line = line.rstrip()
            log_file.write(line + "\n")
            log_file.flush()
        except KeyboardInterrupt:
            proc.terminate()
            break
        line = line.decode('utf-8')
        line = replace_tab_to_space(line)
        #print "{Red}log=>{Color_Off}".format(**Color), line
        lline = line.lower()
        if ("warn" in lline or 'error' in lline
                or 'exception' in lline) and lline.lstrip() == lline:
            COLOR = "Yellow" if "warn" in lline else "Red"
            sys.stdout.write((u"{%s}{line}{Color_Off}{ClearEnd}\n" %
                              COLOR).format(line=line,
                                            **Color).encode('utf-8'))

        else:
            if len(line) >= width:
                line = line[:width - 4] + '...'
            progress = matcher.match(lline)
            if progress is not None:
                show_with_progress_bar(line, progress, width)
            else:
                sys.stdout.write(u"{line}{ClearEnd}{ret}".format(
                    line=line, **Color).encode('utf-8'))
        sys.stdout.flush()
    print
    log_file.close()
    try:
        proc.wait()
    except KeyboardInterrupt:
        proc.kill()
        return 1
    return proc.returncode
예제 #22
0
def print_notification(text):
    '''
    Function prints notification about current game status.
    Input: 
        text - text string
    Return: none
    '''
    cols, rows = terminalsize.get_terminal_size()
    sys.stdout.write("\033[{};{}H".format(rows,0))
    sys.stdout.write(text)
    sys.stdout.flush()
예제 #23
0
파일: wordgame.py 프로젝트: wgml/wordgame
    def __init__(self, dim=15):
        self.size = dim
        self.board = None
        #self.loadedWords = ["word", "test", "another", "much", "words", "blue", "etc"] #todo
        self.terminalSize = terminalsize.get_terminal_size()
        self.getchar = _Getch()
        self.cls = ClearScreen()

        self.loadWords()

        self.manageMenu()
예제 #24
0
def print_notification(text):
    '''
    Function prints notification about current game status.
    Input: 
        text - text string
    Return: none
    '''
    cols, rows = terminalsize.get_terminal_size()
    sys.stdout.write("\033[{};{}H".format(rows, 0))
    sys.stdout.write(text)
    sys.stdout.flush()
예제 #25
0
    def __init__(self):
        self._lines = ['']
        self._cur_row = 0
        self._terminal_width = terminalsize.get_terminal_size()[0]

        if os.name == 'nt':
            # On Windows cmd, control codes must be explicitly enabled.
            ctypes.windll.kernel32.SetConsoleMode(
                ctypes.windll.kernel32.GetStdHandle(-12), 7)

        self.output_written = False
예제 #26
0
파일: wordgame.py 프로젝트: wgml/wordgame
    def __init__(self, dim = 15):
        self.size = dim
        self.board = None
        #self.loadedWords = ["word", "test", "another", "much", "words", "blue", "etc"] #todo
        self.terminalSize = terminalsize.get_terminal_size()
        self.getchar = _Getch()
        self.cls = ClearScreen()

        self.loadWords()

        self.manageMenu()
예제 #27
0
def print_top_right(text):
    '''
    print text to top right in terminal
    '''
#TODO - display multi-line messages
    (width, heigth) = terminalsize.get_terminal_size()  # @UnusedVariable
    text_len = len(text)
    text = '| %s |' % text
    print_there(1, width - len(text) + 1, '+%s+' % ('-' * (text_len + 2)))
    print_there(2, width - len(text) + 1, text)
    print_there(3, width - len(text) + 1, '+%s+' % ('-' * (text_len + 2)))
예제 #28
0
    def set_status(cls, *args):
        """Put text in the status line."""
        width, _ = get_terminal_size()
        text = u' '.join([unicode(a) for a in args])
        text = clip(text, width - 2)

        cls.status_window.move(2, 1)
        cls.status_window.clrtoeol()
        cls.status_window.addstr(2, 1, encoder(text))
        cls.status_window.border()
        cls.status_window.refresh()
예제 #29
0
 def printwords(self):
     """Nicely print words in columns, sensitive to console width!"""
     (console_width, console_height) = terminalsize.get_terminal_size()
     if len(self.wordlist) > 0:
         word_length = max([len(word) for word in self.wordlist]) + 1
         columns = console_width / word_length
         for index, word in enumerate(self.wordlist):
             if (index+1) % columns == 0:
                 print
             print word.ljust(word_length),
     print "\n%d words in list" % len(self.wordlist)
예제 #30
0
 def printwords(self):
     """Nicely print words in columns, sensitive to console width!"""
     (console_width, console_height) = terminalsize.get_terminal_size()
     if len(self.wordlist) > 0:
         word_length = max([len(word) for word in self.wordlist]) + 1
         columns = console_width / word_length
         for index, word in enumerate(self.wordlist):
             if (index+1) % columns == 0:
                 print
             print word.ljust(word_length),
     print "\n%d words in list" % len(self.wordlist)
예제 #31
0
파일: matrix.py 프로젝트: yashunsky/matrix
    def __init__(self):
        self.stdout = sys.stdout
        self.width, self.height = get_terminal_size()
        self.buffers = ['' for i in xrange(self.width)]
        self.speed = [randint(-SPEED_RANGE, MAX_SPEED) 
                      for i in xrange(self.width)]
        self.in_matrix = True
        self.counter = 0
        self.animation_thread = Thread(target=self.animation)
        self.clrscr()

        self.animation_thread.start()
예제 #32
0
파일: matrix.py 프로젝트: yashunsky/matrix
    def __init__(self):
        self.stdout = sys.stdout
        self.width, self.height = get_terminal_size()
        self.buffers = ['' for i in xrange(self.width)]
        self.speed = [
            randint(-SPEED_RANGE, MAX_SPEED) for i in xrange(self.width)
        ]
        self.in_matrix = True
        self.counter = 0
        self.animation_thread = Thread(target=self.animation)
        self.clrscr()

        self.animation_thread.start()
예제 #33
0
    def update_size(self):
        # get terminal size
        size = terminalsize.get_terminal_size()
        self.x = max(size[0], 10)
        self.y = max(size[1], 25)

        # update intendations
        curses.resizeterm(self.y, self.x)
        self.startcol = int(float(self.x) / 5)
        self.indented_startcol = max(self.startcol - 3, 0)
        self.update_space()
        self.screen.clear()
        self.screen.refresh()
예제 #34
0
파일: ui.py 프로젝트: hoyho/musicbox
 def update_size(self):
     # get terminal size
     size = terminalsize.get_terminal_size()
     self.x = max(size[0], 10)
     self.y = max(size[1], 25)
     
     # update intendations
     curses.resizeterm(self.y, self.x)
     self.startcol = int(float(self.x)/5)
     self.indented_startcol = max(self.startcol - 3, 0)
     self.update_space()
     self.screen.clear()
     self.screen.refresh()
예제 #35
0
def pprint(thing, stream=None, indent=4, width=None, depth=0):
    if stream is None:
        stream = sys.stdout
    indent = int(indent)
    if width is None:
        (width, _) = get_terminal_size()
    else:
        width = int(width)

    if _needs_pprint(thing):
        stream.write(_format(thing, indent, width, depth) + '\n')
    else:
        stream.write(repr(thing) + '\n')
예제 #36
0
    def print_list(self):
        colorama.init()
        sizex, sizey = terminalsize.get_terminal_size()
        sizex -= 5
        # Print active tasks
        tlen = 9 + 10 + 20 + 3
        clen = sizex - tlen
        fmtstr = (
            "%(id)3s | %(content)-"
            + str(clen)
            + "s | %(due)-20s | %(priority)-10s"
            + Fore.RESET
            + Back.RESET
            + Style.RESET_ALL
        )
        print Back.WHITE + Fore.BLACK + fmtstr % {"id": "#", "content": "Task", "due": "Due", "priority": "Priority"}

        if len(self.activetasks) == 0:
            print "There are no active tasks. Use the 'Add' command to to one."
        else:
            c = 0
            for t in self.activetasks:
                numlines = int(len(t.content) / (clen)) + 1
                col1 = c
                col2 = ""
                col3 = time.strftime("%H:%M:%S %d/%m/%Y", time.localtime(t.duedate))
                col4 = t.priority
                start = 0
                for i in range(numlines):

                    end = start + clen
                    if end < len(t.content):
                        while end > 0:
                            if t.content[end].isspace():
                                break
                            end -= 1
                        if end == 0:
                            end = start + clen
                    col2 = (t.content[start:end]).strip()
                    start = end
                    print self.priorityStyles[t.priority] + fmtstr % {
                        "id": col1,
                        "content": col2,
                        "due": col3,
                        "priority": col4,
                    }
                    col1 = col3 = col4 = ""
                c += 1

        print ""
예제 #37
0
	def __init__(self):
		self.log_dir = RUN_DIR +'log'
		self.error_log =  self.log_dir + '/error.txt'
		self.success_log = self.log_dir + '/success.txt'
		self.debug_log = self.log_dir + '/debug.txt'
		self.term_width = get_terminal_size()[0]
		
		if not os.path.exists(self.log_dir):
			os.mkdir(self.log_dir)
		elif os.path.isfile(self.log_dir):
			sys.stderr.write('Failed to create log directory: file with name %s, exists!\n' % (os.path.abspath(self.log_dir)))
			exit(1)
		elif not os.path.isdir(self.log_dir):
			sys.stderr.write('Unknown error creating log directory with name %s\n' % (os.path.abspath(self.log_dir)))
			exit(1)
예제 #38
0
    def __init__(self, stdscr):
        """Init."""
        self.stdscr = stdscr

        self.quit = False
        self.paused = False

        self.selection_mode = None
        self.timeline_selection_index = -1
        self.timeline_selection_timestamp = -1
        self.detail_selection_index = -1
        self.detail_selection_timestamp = -1

        self.detail_selection_timestamp = -1

        self.detail_length = 0
        self.detail_data_window = None
        self.timeline_data_window = dict()

        self.sections = list()

        self.header_layout = None
        self.timeline_layout = None
        self.details_layout = None
        self.status_layout = None

        self.header_win = None
        self.timeline_win = None
        self.details_win = None
        self.status_win = None

        self.header_win_border = (0, 0, 0, 0, 0, 0, curses.ACS_LTEE,
                                  curses.ACS_RTEE)
        self.timeline_win_border = (0, 0, ' ', 0, curses.ACS_VLINE,
                                    curses.ACS_VLINE, curses.ACS_VLINE,
                                    curses.ACS_VLINE)
        self.details_win_border = (0, 0, ' ', 0, curses.ACS_VLINE,
                                   curses.ACS_VLINE, 0, 0)
        self.status_win_border = (0, 0, 0, 0, 0, 0, 0, 0)

        self.windows = list()

        self.height, self.width = get_terminal_size()

        self.create()
        self.content()
        self.border()
        self.refresh()
예제 #39
0
    def __init__(
            self, simulation, screen_size=None, offset=(0,0),
            squeeze_factor=2.5, scale_factor=None, trails=3):
        if screen_size:
            self.screen_size = screen_size
        else:
            self.screen_size = list(get_terminal_size())
        

        # print(self.screen_size)
        # exit()
        self.offset = offset
        self.simulation = simulation
        self.squeeze_factor = squeeze_factor
        self.scale_factor = min(self.screen_size)
        self.screen = DecayScreen(self.screen_size)
예제 #40
0
    def do_about(self, args):
        '''about

           Tells you what this software is about'''
        (console_width, console_height) = terminalsize.get_terminal_size()
        for par in ['''\
            This tool, developed by NeCo Corporation, is designed to assist users with
            auditing RobCo TERMLINK security installations, which are notorious for
            flawed in-memory security.
            ''','','''
            Weaker passwords, usually 4 characters in length, are trivial and may not
            require much forethought. However, when encountered with strong security
            with no additional memory access attempts or filtering out improbable
            ciphers, it becomes more cumbersome for a security auditor or technician
            to service the system. This tool was therefore created.
            ''']:
            print textwrap.fill(textwrap.dedent(par), console_width)
def execute(workload_result_file, command_lines):
    proc = subprocess.Popen(" ".join(command_lines), shell=True, bufsize=1, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
    count = 100
    last_time=0
    log_file = open(workload_result_file, 'w')
    # see http://stackoverflow.com/a/4417735/1442961
    lines_iterator = iter(proc.stdout.readline, b"")
    for line in lines_iterator:
        count += 1
        if count > 100 or time()-last_time>1: # refresh terminal size for 100 lines or each seconds
            count, last_time = 0, time()
            width, height = get_terminal_size()
            width -= 1

        try:
            line = line.rstrip()
            log_file.write(line+"\n")
            log_file.flush()
        except KeyboardInterrupt:
            proc.terminate()
            break
        line = line.decode('utf-8')
        line = replace_tab_to_space(line)
        #print "{Red}log=>{Color_Off}".format(**Color), line
        lline = line.lower()
        if ("warn" in lline or 'err' in lline or 'exception' in lline) and lline.lstrip() == lline:
            COLOR="Yellow" if "warn" in lline else "Red"
            sys.stdout.write((u"{%s}{line}{Color_Off}{ClearEnd}\n" % COLOR).format(line=line,**Color).encode('utf-8'))
            
        else:
            if len(line) >= width:
                line = line[:width-4]+'...'
            progress = matcher.match(lline)
            if progress is not None:
                show_with_progress_bar(line, progress, width)
            else:
                sys.stdout.write(u"{line}{ClearEnd}\r".format(line=line, **Color).encode('utf-8'))
        sys.stdout.flush()
    print
    log_file.close()
    try:
        proc.wait()
    except KeyboardInterrupt:
        proc.kill()
        return 1
    return proc.returncode
예제 #42
0
    def do_about(self, args):
        '''about

           Tells you what this software is about'''
        (console_width, console_height) = terminalsize.get_terminal_size()
        for par in ['''\
            This tool, developed by NeCo Corporation, is designed to assist users with
            auditing RobCo TERMLINK security installations, which are notorious for
            flawed in-memory security.
            ''','','''
            Weaker passwords, usually 4 characters in length, are trivial and may not
            require much forethought. However, when encountered with strong security
            with no additional memory access attempts or filtering out improbable
            ciphers, it becomes more cumbersome for a security auditor or technician
            to service the system. This tool was therefore created.
            ''']:
            print textwrap.fill(textwrap.dedent(par), console_width)
예제 #43
0
파일: ui.py 프로젝트: tsiegleauq/musicbox
 def __init__(self):
     self.screen = curses.initscr()
     # charactor break buffer
     curses.cbreak()
     self.screen.keypad(1)
     self.netease = NetEase()
     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_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()
예제 #44
0
 def __init__(self):
     self.screen = curses.initscr()
     # charactor break buffer
     curses.cbreak()
     self.screen.keypad(1)
     self.netease = NetEase()
     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_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()
예제 #45
0
    def layout(self):
        """Calculate the sizes and locations of the windows."""
        self.width, self.height = get_terminal_size()

        header_height = 3
        timeline_height = 8
        status_height = 4
        details_height = self.height - header_height - timeline_height - status_height

        header_start = 0
        timeline_start = header_height
        details_start = timeline_start + timeline_height
        status_start = details_start + details_height

        self.header_layout = (header_height, self.width, header_start, 0)
        self.timeline_layout = (timeline_height, self.width, timeline_start, 0)
        self.details_layout = (details_height, self.width, details_start, 0)
        self.status_layout = (status_height, self.width, status_start, 0)
예제 #46
0
def printWithCursor(prompt, line, cursor):
    if cursor == len(line):
        line += ' '
    chars, [cursor] = eastAsianStrSparse(line, [cursor])
    chars[cursor] = CURSOR_WRAP % chars[cursor]
    width = get_terminal_size()[0] - eastAsianStrLen(prompt) - 1
    offset = min(cursor - width // 2, len(chars) - width)
    if offset > 0:
        chars = chars[offset + ABBR_LEN:]
        if chars[0] == '':
            chars.pop(0)
        chars = ABBR + [' '] + chars
    offset = len(chars) - width
    if offset > 0:
        if chars[-offset] == '':
            offset += 1
        chars = chars[:-offset - ABBR_LEN]
        chars += [' '] + ABBR
    line = ''.join(chars)
    print(prompt, printabilize(line), end='\r', flush=True, sep='')
예제 #47
0
def imprimir(secadora,color='blanco'):
	global esclavo
	width,height=terminalsize.get_terminal_size()
	if width >87:
		sys.stdout.write('\0\033[' + str(esclavo[secadora].renglon) + ';1H')
		if color=='blanco':
			sys.stdout.write('\0\033[1;37m')
		if color=='verde':
			sys.stdout.write('\0\033[1;32m')
		if color=='amarillo':
			sys.stdout.write('\0\033[1;33m')
		printw(esclavo[secadora].nombre)
		printw(esclavo[secadora].temp1,8)
		printw(esclavo[secadora].temp2,8)
		printw(esclavo[secadora].entrada1,3)
		printw(esclavo[secadora].entrada2,3)
		printw(esclavo[secadora].formula)
		printw(esclavo[secadora].display,width-87)
		printw(str(esclavo[secadora].version))
		printw(str(esclavo[secadora].tiemporespuesta),17)
		printw(str(esclavo[secadora].tiemporespuestas),17)
예제 #48
0
def _get_finish_text():
    """ Returns suitable text based on window-size """
    txt = """
    /        |/      |/  \     /  |/        |      /      | /      \       /  |  /  |/       \ 
   $$$$$$$$/ $$$$$$/ $$  \   /$$ |$$$$$$$$/       $$$$$$/ /$$$$$$  |      $$ |  $$ |$$$$$$$  |
    $$ |     $$ |  $$$  \ /$$$ |$$ |__            $$ |  $$ \__$$/       $$ |  $$ |$$ |__$$ |
    $$ |     $$ |  $$$$  /$$$$ |$$    |           $$ |  $$      \       $$ |  $$ |$$    $$/ 
    $$ |     $$ |  $$ $$ $$/$$ |$$$$$/            $$ |   $$$$$$  |      $$ |  $$ |$$$$$$$/  
    $$ |    _$$ |_ $$ |$$$/ $$ |$$ |_____        _$$ |_ /  \__$$ |      $$ \__$$ |$$ |      
    $$ |   / $$   |$$ | $/  $$ |$$       |      / $$   |$$    $$/       $$    $$/ $$ |      
    $$/    $$$$$$/ $$/      $$/ $$$$$$$$/       $$$$$$/  $$$$$$/         $$$$$$/  $$/  
    Press CTRL + C to exit
    """
    x, y = get_terminal_size()

    if y > 9 and x > 94:
        return txt

    txt = """
 _______  _                       _                        
(__ _ __)(_)             ____    (_) ____                  
   (_)    _   __   __   (____)    _ (____)    _   _  ____  
   (_)   (_) (__)_(__) (_)_(_)   (_)(_)__    (_) (_)(____) 
   (_)   (_)(_) (_) (_)(__)__    (_) _(__)   (_)_(_)(_)_(_)
   (_)   (_)(_) (_) (_) (____)   (_)(____)    (___) (____) 
                                                    (_)    
                                                    (_)
    """
    if y > 9 and x > 58:
        return txt

    txt = """
       ╔╦╗┬┌┬┐┌─┐  ┬┌─┐  ┬ ┬┌─┐
        ║ ││││├┤   │└─┐  │ │├─┘
        ╩ ┴┴ ┴└─┘  ┴└─┘  └─┘┴  
    """
    if y > 4 and x > 25:
        return txt

    return 'Time is up!'
예제 #49
0
    def do_license(self, args):
        '''license
           This software is provided to you under the C.I.T. License.

           Type "license" to see actual LEGAL JIBBER JABBERS.'''
        (console_width, console_height) = terminalsize.get_terminal_size()
        for par in ['''\
            This software is provided to you under the C.I.T. License.
            ''','''\
            (also known outside the Commonwealth as MIT License)
            ''','','''\
            Copyright (c) 2015 Chawanat Nakasan
            ''','','''\
            Permission is hereby granted, free of charge, to any person obtaining a copy
            of this software and associated documentation files (the "Software"), to deal
            in the Software without restriction, including without limitation the rights
            to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
            copies of the Software, and to permit persons to whom the Software is furnished
            to do so, subject to the following conditions:
            ''','','''\
            The above copyright notice and this permission notice shall be included in all
            copies or substantial portions of the software.
            ''','','''\
            THIS SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
            IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
            FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
            AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGERS OR OTHER
            LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
            OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
            SOFTWARE.
            ''','','''\
            Actually I'm not that serious about license. Just wanted an excuse to say C.I.T. somewhere.
        ''','','''\
            Bethesda, Bethesda Softworks, Bethesda Game Studios, Fallout, PIP-BOY,
            Vault-Boy character, and Dogmeat are property of Bethesda Softworks.
            Other trademarks and intellectual properties are owned by their respective
            owners. This is a fan program and is not endorsed by any entities aforementioned.
            ''']:
            print textwrap.fill(textwrap.dedent(par), console_width)
예제 #50
0
 def update(self, new_done, symbol='*', getSuffix=None, flush=False):
     if not self.active:
         raise JdtAlreadyClosedError
     self.done = new_done
     if not flush and self.UPP_count != self.UPP:
         self.UPP_count += 1
         return
     self.UPP_count = 0
     if self.goal == 0:
         progress = 1
     else:
         progress = new_done / self.goal
     terminal_width = get_terminal_size()[0] - 4
     if getSuffix is None:
         getSuffix = self.getSuffix
     suffix = getSuffix(new_done, progress)
     msg_and_bar_width = terminal_width - len(suffix)
     msg_width = min(len(self.msg), int(msg_and_bar_width / 2))
     msg_to_print = self.msg[-msg_width:]
     bar_width = msg_and_bar_width - msg_width
     if bar_width < self.MIN_BAR_WIDTH:
         bar_width = terminal_width - 2
         msg_to_print = ''
         suffix = ''
     bar_inner_width = bar_width - 2
     bar_fill_width = int(bar_inner_width * progress)
     bar_empty_width = bar_inner_width - bar_fill_width
     print('\r',
           msg_to_print,
           ' ',
           '[',
           symbol * bar_fill_width,
           '_' * bar_empty_width,
           ']',
           ' ',
           suffix,
           sep='',
           end='',
           flush=True)
예제 #51
0
def refresco_pantalla():
	global esclavollamada
	global totalesclavos
	r=''
	while True:
		width,height=terminalsize.get_terminal_size()
		maxlista=height - totalesclavos -1
		if maxlista > 1:
			escribir (totalesclavos + 1, '-'*(width-1))
			while len(datosrespuestas) > maxlista:
				datosrespuestas.pop(0)	
			while len(respuestas) > maxlista:
				respuestas.pop(0)
			i=1
			for x in respuestas:
				i=i+1
				escribir(i + totalesclavos,x)
			i=1
			for x in datosrespuestas:
				i=i+1
				if width > 60:
					if len(x) - 16 > width - 32:
						escribir(i + totalesclavos,x[:width - 16],32)
					else:
						escribir(i + totalesclavos,x + (width - 32 - (len(x)-16)) * ' ',32)				
		for i in esclavo:
			ahora=datetime.datetime.now()
			if int((ahora - esclavo[i].ultimarespuesta).seconds) < alertaverde:
				imprimir(i,'verde')
			elif int((ahora - esclavo[i].ultimarespuesta).seconds) < alertaamarilla:
				imprimir(i)
			elif int((ahora - esclavo[i].ultimarespuesta).seconds) < alertaroja:
				esclavo[i].tiemporespuestas=datetime.datetime.now()-esclavo[i].ultimarespuesta
				imprimir(i,'amarillo')
			else:
				borrar(i)
예제 #52
0
파일: pytrans.py 프로젝트: ray-chu/pytrans
 def query(self,word):
    width, height = terminalsize.get_terminal_size()
    dividing_line="-"*width+'\n'
    print dividing_line
    url=self.url_base+word
    response=requests.get(url)
    text_codec=response.encoding
    #print response.text.encode(response.encoding)
    root=ET.fromstring(response.text.encode(response.encoding))
    ### tags needs to be processed
    ### tags=['errorCode','basic','translation','web']
    ### error code 
    error_code=root.find('errorCode')
    if(error_code.text=='20'):
       print "You are so verbose. Queried string must be shorter than 200."
    elif(error_code.text=='30'):
       print "Life is imperfect. So we simply cannot find the translations for this word."
    elif(error_code.text=='40'):
       print "Which language are you querying? Currently we just support Chinese and English."
    elif(error_code.text=='50'):
       print "Obviously, the developer of this app is a poor guy. He doesn't have a vaild key. And Youdao is very mean."
    if(error_code.text!='0'):
       return
    ### query key
    query_key=root.find('query')
    if(query_key.text):
       print (color.BOLD+query_key.text+color.END+"    "+color.GREY+"Source: "+self.source+color.END)
    else:
       return
    ### basic dictionary
    basic=root.find('basic')
    if(basic is not None):
       uk_phonetic=basic.find('uk-phonetic')
       if(uk_phonetic is not None):
          print(color.RED+u"英[ "+uk_phonetic.text+" ]  "+color.END),
       us_phonetic=basic.find('us-phonetic')
       if(us_phonetic is not None):
          print(color.RED+u"美[ "+us_phonetic.text+" ]")
       print ""
       explains=basic.findall('explains')      
       if(explains is not None):
          for expl in explains:
             exs=expl.findall('ex')
             if(exs is not None):
                for ex in exs:
                   print ('- '+color.GREEN+ex.text+' '+color.END)
          print ""
    ### Youdao translate
    translation=root.find('translation')
    if(translation is not None):
       print (color.GREY+u"-- 有道翻译 --"+color.END)
       paras=translation.findall('paragraph')
       if(paras is not None):
          for para in paras:
             print ('- '+color.GREEN+para.text+' '+color.END)
          print ""
    ### Web search
    web=root.find('web')
    if(web is not None):
       print (color.GREY+u"-- 网络释义 --"+color.END)
       explains=web.findall('explain')
       if(explains is not None):
          for expl in explains:
             key=expl.find('key')
             if(key is not None):
                print (key.text+" - "),
             value=expl.find('value')
             if(value is not None):
                exs=value.findall('ex')
                if(exs is not None):
                   for ex in exs:
                      print (color.CYAN+ex.text+color.END),
             print ""
예제 #53
0
def splashscreen():
	width,height=terminalsize.get_terminal_size()
	os.system('img2txt --width='+ str(width) + ' --height=' + str(height - 2) + ' dryermon.jpg')
	datosrespuestas.append('\0\033[1;32m' + str(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'))+ '\0\033[1;31m' + ' * Creado por [email protected] *')
	datosrespuestas.append('\0\033[1;32m' + str(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'))+ '\0\033[1;31m' + ' * Proyectos de automatizacion H&H *')	
	time.sleep(5)		
예제 #54
0
파일: crt.py 프로젝트: pennyarcade/pyhack
def _get_screen_width():
    result = terminalsize.get_terminal_size()
    return result[0]
예제 #55
0
파일: duviz.py 프로젝트: fire-eggs/duviz
def getTerminalSize():
    global terminal_width
    os.system("mode con lines=40 cols=130")  # TODO hack for debugging
    terminal_width, ignore  = get_terminal_size()
    terminal_width -= 1 # seems to be necessary on windows? \r vs \r\n ?
예제 #56
0
def execute(workload_result_file, command_lines):
    proc = subprocess.Popen(" ".join(command_lines), shell=True, bufsize=1, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
    count = 100
    last_time=0
    log_file = open(workload_result_file, 'w')
    # see http://stackoverflow.com/a/4417735/1442961
    lines_iterator = iter(proc.stdout.readline, b"")
    for line in lines_iterator:
        count += 1
        if count > 100 or time()-last_time>1: # refresh terminal size for 100 lines or each seconds
            count, last_time = 0, time()
            width, height = get_terminal_size()
            width -= 1

        try:
            line = line.rstrip()
            log_file.write(line+"\n")
            log_file.flush()
        except KeyboardInterrupt:
            proc.terminate()
            break
        line = line.decode('utf-8')
        line = replace_tab_to_space(line)
        #print "{Red}log=>{Color_Off}".format(**Color), line
        lline = line.lower()

        def table_not_found_in_log(line):
            table_not_found_pattern = "*Table * not found*"
            regex = fnmatch.translate(table_not_found_pattern)
            reobj = re.compile(regex)
            if reobj.match(line):
                return True
            else:
                return False

        def database_default_exist_in_log(line):
            database_default_already_exist = "Database default already exists"
            if database_default_already_exist in line:
                return True
            else:
                return False

        def uri_with_key_not_found_in_log(line):
            uri_with_key_not_found = "Could not find uri with key [dfs.encryption.key.provider.uri]"
            if uri_with_key_not_found in line:
                return True
            else:
                return False

        if ('error' in lline) and lline.lstrip() == lline:
            #Bypass hive 'error's and KeyProviderCache error
            bypass_error_condition = table_not_found_in_log or database_default_exist_in_log(lline) or uri_with_key_not_found_in_log(lline)
            if not bypass_error_condition:
                COLOR = "Red"
                sys.stdout.write((u"{%s}{line}{Color_Off}{ClearEnd}\n" % COLOR).format(line=line,**Color).encode('utf-8'))
            
        else:
            if len(line) >= width:
                line = line[:width-4]+'...'
            progress = matcher.match(lline)
            if progress is not None:
                show_with_progress_bar(line, progress, width)
            else:
                sys.stdout.write(u"{line}{ClearEnd}{ret}".format(line=line, **Color).encode('utf-8'))
        sys.stdout.flush()
    print
    log_file.close()
    try:
        proc.wait()
    except KeyboardInterrupt:
        proc.kill()
        return 1
    return proc.returncode
예제 #57
0
파일: crt.py 프로젝트: pennyarcade/pyhack
def _get_screen_height():
    result = terminalsize.get_terminal_size()
    return result[1]
예제 #58
0
#!/usr/bin/env python
# -- coding: utf-8 --

import os, sys, logging, random, re
import tweetpony
from time import strftime
from terminalsize import get_terminal_size

logging.getLogger("requests").setLevel(logging.WARNING) #Disable Requests' log spam
logging.basicConfig(filename="pygenwalder.log", level=logging.DEBUG)
logger = logging.getLogger()

ts = get_terminal_size()
twidth = ts[0]

#https://dev.twitter.com/discussions/19096 #hooray for unicode

title = "PygenwalderBot"

consumer_key = ""
consumer_secret = ""
access_token = ""
access_token_secret = ""

responses = ["Rügenwalder.", "Teewurst?", "Diese hier?", "Die mit der Mühle.", "Alle."]
keywords = ["teewurst", "rügenwalder", "rugenwalder", "ruegenwalderbot"]
ignoredusers = []

randomresponse = ""
def get_random_response():
	global randomresponse
예제 #59
0
def termianlmsg(paragraphs, wallchar="*"):
    (width, height) = get_terminal_size()

    print wallchar * width
    print wallchar, wallchar.rjust(width - len(wallchar) * 2 - 2)