def print_progress(iteration, total, prefix='', suffix='', decimals=1, bar_length=100): """ Call in a loop to create terminal progress bar @params: iteration - Required : current iteration (Int) total - Required : total iterations (Int) prefix - Optional : prefix string (Str) suffix - Optional : suffix string (Str) decimals - Optional : positive number of decimals in percent complete (Int) bar_length - Optional : character length of bar (Int) """ if iteration == 0: cursor.hide() bar_length = shutil.get_terminal_size()[0] // 2 str_format = "{0:." + str(decimals) + "f}" percents = str_format.format(100 * (iteration / float(total))) filled_length = int(round(bar_length * iteration / float(total))) bar = '+' * filled_length + '-' * (bar_length - filled_length) progress_bar = "\r%s |%s| %s%s %s" % (prefix, bar, percents, '%', suffix) print(progress_bar, end='', flush=True) if iteration == total: print("") cursor.show()
def animated_loading(flag): if (flag == 0): msg = "loading dataframe " chars = "▁▂▃▄▅▆▇█▇▆▅▄▃▁" if (flag == 1): chars = "◢ ◣ ◤ ◥" msg = "removing incosistency " if (flag == 2): chars = "▖▘▝▗" msg = "inserting metadata " if (flag == 3): chars = "▖▘▝▗" msg = "finding geo info " cursor.hide() if (flag == 4): chars = "⣾⣽⣻⢿⡿⣟⣯⣷" msg = "saving dataframe " cursor.hide() for char in chars: sys.stdout.write('\r' + msg + '' + char) time.sleep(.1) sys.stdout.flush() cursor.show()
def do(index, writer): cursor.hide() result = review(data, index) print(f"Done with {index}/{total}. That's {((index/total)*100):.2f}%") print( f"{color.BOLD}Do over? ({color.RED}Y(0){color.END}/{color.BOLD}{color.GREEN}N(1){color.END}{color.BOLD}){color.END} or quit (Q)" ) do = getch.getch() if do == 'Q': cursor.show() return [index, True] while do == 'Y' or do == '0': result = review(data, index) print(f"Done with {index}/{total}. That's {((index/total)*100):.2f}%") print( f"{color.BOLD}Do over? ({color.RED}Y(0){color.END}/{color.BOLD}{color.GREEN}N(1){color.END}{color.BOLD}){color.END} or quit (Q)" ) do = getch.getch() writer.writerow([ index, REVIEWER, result["model"], result["isPsych"], result["botRubric"]["clarity"], result["botRubric"]["specificity"], result["botRubric"]["psycology"], result["humanRubric"]["clarity"], result["humanRubric"]["specificity"], result["humanRubric"]["psycology"], result["botTuring"], result["humanTuring"] ]) cursor.show() return [index, False]
def go_loop(): init_main() cursor.hide() global active global anchor global is_anchor_changed global menu_actions global menu_str looping = True while looping: menu_actions = get_action_from_menu(menu) menu_str = get_str_from_menu(menu) print_menu() while not kbhit(): pass c = getwch().encode('utf8') if c in [b'\xc3\xa0', b'\x00']: c = getwch().encode('utf8') if c == b'H': up(len(menu)) if c == b'P': down(len(menu)) if c == b'\r': is_anchor_changed = True clear() looping = menu_actions[active[0]]()
def __call__(self, *message): """ Log the given MESSAGE. This will overwrite the previous outputed message. You can provide several arguments, they will be joined with a space character """ if not self.show_cursor: cursor.hide() paragraphs = [ wrap( line, get_terminal_size().columns or 80, drop_whitespace=False, # trim replace_whitespace=False, break_long_words=False) # wordWrap for line in " ".join(message).splitlines() ] lines = [l for line in paragraphs for l in line] self.stream.write( erase_lines(self.prev_line_count) + "\n".join(lines) + "\n") self.prev_line_count = 1 + len(lines) return self
def progressBar(completed_tasks_ref, total_tasks): """\ displays a progress bar based on number of tasks completed and returns 0 when completed_tasks_ref == total_tasks Arguments: completed_tasks_ref --- reference to the variable that holds the total number of completed tasks. only read to prevent threading conflicts total_tasks --- total number of tasks """ cursor.hide() bar_width = 30 while completed_tasks_ref["tasks"] < total_tasks: completed_tasks = completed_tasks_ref["tasks"] num_ticks = int(ceil(bar_width * (completed_tasks / total_tasks))) num_blank = bar_width - num_ticks sys.stdout.write("[" + "=" * num_ticks + " " * num_blank + "]") sys.stdout.flush() sleep(0.01) sys.stdout.write("\b" * (bar_width + 2)) sys.stdout.flush() sys.stdout.write("[" + "=" * bar_width + "]" + "\n\n") sys.stdout.flush() cursor.show() return 3
def _render(self): # # obtains console width for dynamic center align # try: # width = os.get_terminal_size().columns # except OSError: # width = sys.maxsize num = 0 render = "" for item in self.options: string = item[0] if self.location == num: string = formatters.formatters.bold + "■" + string else: string = formatters.formatters.default + "□" + string # string = string.ljust(width) # dynamic center align string = string.center(70) # centers with the logo render = render + string + "\n" num += 1 # stops console from flickering from rapid reprints if render != self.lastRender: if self.CoreLoop is not None: self.CoreLoop.clearScreen() else: os.system("cls") cursor.hide() optInString = "=={} members are opted in==\n".format(len(self.CoreLoop.targetPool)) print(optInString.center(65) + "\n") print(render) self.lastRender = render
def main(): cursor.hide() ################################ fps = float(40) # frameDelay = float(1000 / fps) # ################################ menu = Menu(menupontok) menu.kirajzol() game = Game() run = True while run: ################################################# starting_time = float(time.time() * 1000) # ################################################# game.run() if not game.fut: run = False ############################################################# taken_time = float(time.time() * 1000) - starting_time # if frameDelay > taken_time: # time.sleep(float((frameDelay - taken_time) / 1000)) #
def download(self, download: Download): cursor.hide() if not os.path.isdir(Rf'{tempfile.gettempdir()}\electric'): os.mkdir(Rf'{tempfile.gettempdir()}\electric') path = Rf'{tempfile.gettempdir()}\electric\{download.name}{download.extension}' with open(path, 'wb') as f: response = requests.get(download.url, stream=True) total_length = response.headers.get('content-length') if total_length is None: f.write(response.content) else: dl = 0 full_length = int(total_length) for data in response.iter_content(chunk_size=4096): dl += len(data) f.write(data) complete = int(20 * dl / full_length) fill_c, unfill_c = '█' * complete, ' ' * (20 - complete) try: sys.stdout.write( f"\r[{fill_c}{unfill_c}] ⚡ {round(dl / full_length * 100, 1)} % ⚡ {round(dl / 1000000, 1)} / {round(full_length / 1000000, 1)} MB") except UnicodeEncodeError: pass sys.stdout.flush() paths.update({download.display_name: {'path': path, 'display_name': download.display_name}}) cursor.show()
def main(): """Main loop.""" os.system("cls") cursor.hide() snake = Snake(25, 50) process_key = mp.Process(target=get_key, args=(snake.direction, )) process_key.daemon = True process_key.start() process_render = mp.Process(target=render, args=(snake.grid, )) process_render.daemon = True process_render.start() timer = Timer(10) while not snake.dead: if timer.ready: snake.move() timer.reset() process_key.terminate() process_render.terminate() os.system("cls") cursor.show()
def loop(self, generations=1, toCMD=None, singlePNG=None, singlePNGscale=1, multiPNG=None, multiPNGscale=1, loopLen=5, depth=2): """ Plays the game of life, can print to cmd or save as png's Args: generations: number of iterations toCMD: if True the game will be printed to the command line singlePNG: if True the final outcome will be saved as PNG singlePNGscale: scales the size that one matrix value will take in pixels multiPNG: if True the playthrough will be saved as PNG multiPNGscale: scales the size that one matrix value will take in pixels loopLen: number of matrizes that are recorded going back from most recent depth: how deep list checks for duplicates """ if toCMD: cursor.hide() for i in range(generations + 1): if toCMD: self.toCMD(self.progress[-1], i) if self.caught(depth): print('caught in loop') break if i != generations: self.iterate(self.progress[-1]) if multiPNG: self.toPNG(multiPNGscale) if singlePNG: self.toPNG(singlePNGscale, self.progress[-1]) if toCMD: cursor.show()
def start(self, text=None): """Starts the spinner on a separate thread. Parameters ---------- text : None, optional Text to be used alongside spinner Returns ------- self """ if text is not None: self._text = self._get_text(text, animation=None) if not self._enabled or self._spinner_id is not None: return self if self._stream.isatty(): cursor.hide(stream=self._stream) self._stop_spinner = threading.Event() self._spinner_thread = threading.Thread(target=self.render) self._spinner_thread.setDaemon(True) self._render_frame() self._spinner_id = self._spinner_thread.name self._spinner_thread.start() return self
def input(self, text): show() set_echo(True) res = input(bg("dark_gray") + text) clear() hide() set_echo(False) return res
def main(): cursor.hide() try: preamble() time.sleep(0.5) working_dir = os.getcwd() print() print('This program will use the following directory as the working directory:') print() print(' ' + working_dir) guard_prerequisites(working_dir) time.sleep(0.5) print() cursor.show() base_url = input('Enter a base url for URLs, or leave blank to use the output directory:\n\n ') cursor.hide() print() if '' == base_url: base_url = 'file://' + working_dir + '/output/' run_scripts(working_dir, base_url) time.sleep(0.5) print() print() print('\033[1mThe index has been generated.') time.sleep(0.5) print() print('Thank you for using this program.') time.sleep(0.5) print() print('\033[38;5;155mGood bye!\033[0m') time.sleep(1) except KeyboardInterrupt: print() print() print('Quitting via keyboard interrupt.') print() time.sleep(1) except MissingPrerequisite: print() print() print('Quitting due to failed prerequisites.') print() time.sleep(1) cursor.show()
def terminal_led(dmx_data): """ Send the LED sequence to the terminal for emulation """ cursor.hide() vumeter = "" for i in range(0, len(dmx_data), 3): vumeter = vumeter + color("█", fore=(dmx_data[i:i + 3])) print("\r[" + vumeter + "]", end="")
def main(): print('Press CTRL+C to abort animation') cursor.hide() try: main_loop() except KeyboardInterrupt: cursor.show() os.system('clear')
def take_over(self): clear() self.is_active = True self.drawbg() hide() set_echo(False) reverted = revert_x_to_y(self) for i in reverted: print("".join(i))
def main(team, password, url): api = Api(url, password, team) board = Board(25, 25) cursor.hide() print("\033[2J") initState(api, board) mainLoop(api, board) exit()
def download_dir(self, download_from_dir, upload_to_dir='.', exclude_ext=None, with_root_path=True): cursor.hide() tasks = (self.download_dir_async(download_from_dir, upload_to_dir, exclude_ext, with_root_path), ) asyncio.run(asyncio.wait(tasks)) cursor.show()
def charprint(string, color, cursorused=True, end="\n"): if cursorused == True: cursor.show() for i in string: sys.stdout.write(colored(i, color=color)) sys.stdout.flush() sys.stdout.write(end) sys.stdout.flush() if cursorused == True: cursor.hide()
def spam(text, t): cursor.hide() length = len(text) wait = t / length text = ''.join(filter(whitelist.__contains__, text)) for l in text.lower(): time.sleep(wait) print(color + table[l], end='\r') cursor.show()
def dots(): cursor.hide() time.sleep(5) print("\n\tОбождите.", sep=' ', end='', flush=True) for i in range(10): print(".", sep=' ', end='', flush=True) time.sleep(1) cursor.show() print() start()
def render(self): z = 0 print("\033c", end="") cursor.hide() try: for y in range(self.rows): for x in range(self.cols): print(self.data[z], end="") z = z + 1 print("\n", end="") except: cursor.show() cursor.show()
def __init__(self, chars=1, raw=False): if raw: tty.setraw(FD) else: tty.setcbreak(FD) cursor.hide() self.ch = sys.stdin.read(chars) termios.tcsetattr(FD, termios.TCSADRAIN, SETTINGS) cursor.show()
def animate_network(k=2, leave_trace=False, speed=10): cursor.hide() n = Network(k) n.print_states() n.states[-1] = 'g' while n.states[0] != '!': sleep(1.0/speed) n.print_states(leave_trace) n.update() n.print_states() cursor.show()
def _out(filename): if not is_filename_compliant(filename): return (True, False) _f = open(__EXTENSION__[1:] + "/" + filename + __EXTENSION__, "w") cursor.hide() dots = ("Generating maze ", "Generating maze .", "Generating maze ..", "Generating maze ...") for _t in range(20): print("{}".format(dots[_t % 4]), end="\r") print(" "*len(dots[-1])) cursor.show() print("Done, maze \"" + filename + "\" saved") _f.close() return (True, False)
def main(): global args global videoAudio parser = argparse.ArgumentParser() parser.add_argument("url", help="指定YouTube視訊網址") parser.add_argument("-sd", action="store_true", help="選擇普通(480P)畫質") parser.add_argument("-hd", action="store_true", help="選擇HD(720P)畫質") parser.add_argument("-fhd", action="store_true", help="選擇Full HD(1080P)畫質") parser.add_argument("-a", action="store_true", help="僅下載聲音") args = parser.parse_args() videoAudio = 'video codec' cursor.hide() download_media(args) cursor.show()
def spam(t): text = ''' Needed feebly dining oh talked wisdom oppose at. Applauded use attempted strangers now are middleton concluded had. It is tried no added purse shall no on truth. Pleased anxious or as in by viewing forbade minutes prevent. Too leave had those get being led weeks blind. Had men rose from down lady able. Its son him ferrars proceed six parlors. Her say projection age announcing decisively men. Few gay sir those green men timed downs widow chief. Prevailed remainder may propriety can and. At distant inhabit amongst by. Appetite welcomed interest the goodness boy not. Estimable education for disposing pronounce her. John size good gay plan sent old roof own. Inquietude saw understood his friendship frequently yet. Nature his marked ham wished. ''' cursor.hide() length = len(text) wait = t/length text = ''.join(filter(whitelist.__contains__, text)) for l in text.lower(): time.sleep(wait) print(color + table[l], end='\r') cursor.show()
def loop(): (current, stop) = menu() cursor.hide() while True: if current == -1: # someone pressed ctrl+C during the menu, that's our exit cue print(".") return try: mode = CYCLE[current][0] clear(mode) m = CYCLE[current][1] * 60 if stop: # wait for user to press enter cursor_top() v_center() line(mode, format(m)) exhaust() cursor.show() input() clear(mode) cursor.hide() t0 = time.time() t1 = t0 + m r = 0 send_event(mode, True) while time.time() < t1: diff = t1 - time.time() cursor_top() # some keystrokes leave garbage in the terminal, this cleans it up every 15 cycles r += 1 if r >= GARBAGE_CLEANUP: clear(mode) r = 0 v_center() line(mode, format(diff)) time.sleep(min(INTERVAL_SECONDS, diff)) send_event(mode, False) current = (current + 1) % len(CYCLE) stop = True except KeyboardInterrupt: #allow to restart the menu by using ctrl + c (current, stop) = menu()
def createcanvas(width=round(pyautogui.size()[0] / 8), height=round(pyautogui.size()[1] / 8), fullscreen=True): os.system('mode con: cols=' + str(int(width)) + ' lines=' + str(int(height))) #making it full screen if (fullscreen): pyautogui.press("f11") cursor.hide() os.system('') clear() rows, cols = (width, height) for i in range(cols): col = [] for j in range(rows): col.append(["\u001b[0m", " "]) output.append(col)
def main(): pa = Parser() naam, url, comm = pa.zendervinden() print naam, url, comm cursor.hide() fa = Fabriek() co = fa.returnCommunicatorObject(comm) rd = Radio() t = threading.Thread(target=rd.afspelen, args=(naam, url, co)) t.start() ## Afspelen stoppen na drukken op één van de EXITKEYS kp = Keypress() while kp.getexitkeypress() == False: time.sleep(0.2) cursor.show() rd.stoppen() return 0
# -*- coding: utf-8 -*- """Example for stream changing """ from __future__ import unicode_literals, absolute_import, print_function import os import time import sys os.sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) import cursor cursor.hide(stream=sys.stderr) # Hides the cursor cursor.show(stream=sys.stderr) # Shows the cursor with cursor.HiddenCursor(stream=sys.stderr): # Cursor will stay hidden import time # while code is being executed; for a in range(1, 100): # afterwards it will show up again print(a) time.sleep(0.05)
def init_window(self): self.t = Terminal() print(self.t.civis) if cursor: cursor.hide()