def menu(): """Shows a simple menu.""" menu = 'main' while 1: if menu == 'main': click.echo('Main menu:') click.echo(' d: debug menu') click.echo(' q: quit') char = click.getchar() if char == 'd': menu = 'debug' elif char == 'q': menu = 'quit' else: click.echo('Invalid input') elif menu == 'debug': click.echo('Debug menu') click.echo(' b: back') char = click.getchar() if char == 'b': menu = 'main' else: click.echo('Invalid input') elif menu == 'quit': return
def main(): try: cli.main(standalone_mode=False) except CalledProcessError as e: tty.puterr("`{0}` failed with code {1}".format( " ".join(e.cmd), e.returncode )) except ParserError as e: tty.puterr("Error reading {0} at {1}: {2}".format( e.filetype, e.filepath, e.message )) except BrewMissingError as e: print("Next, install Homebrew (press any key to redirect)") click.getchar() urlopen(e.url) sys.exit(1) except (CiderException, click.ClickException) as e: tty.puterr(e.message, prefix="Error:") sys.exit(e.exit_code) except click.Abort: sys.stderr.write("Aborted!\n") sys.exit(1)
def main(function, df, output, server, all): """ 股票行情获取程序, 作者RainX<*****@*****.**> """ if all: global SERVERS SERVERS = OrderedDict([(idx+1, [host[0], "%s:%s" % (host[1], host[2])]) for idx, host in enumerate(hq_hosts)]) click.secho("连接中.... ", fg="green") if server == '-': connect() else: connect_to(server) click.secho("连接成功!", fg="green") if function == 0: while True: click.secho("-" * 20) click.secho("功能列表:") for (k,v) in FUNCTION_LIST.items(): click.secho(str(k) + " : " + v[0], bold=True) last = k + 1 click.secho(str(last) + " : 退出断开连接", bold=True) click.secho("-" * 20) value = click.prompt('请输入要使用的功能', type=int) if value == last: break run_function(df, value) click.secho("-" * 20) click.echo("按任意键继续") click.getchar() elif function in FUNCTION_LIST.keys(): value = function result = run_function(df, value) if (result is not None) and (output != "-"): click.secho("写入结果到 " + output) if isinstance(result, pd.DataFrame): result.to_csv(output) else: with open(output, "wb") as f: pickle.dump(result, f) click.secho("断开连接中.... ", fg="green") disconnect() click.secho("断开连接成功!", fg="green")
def run_single(file_name=None): # single env controller = RoboThorEnv() state = controller.reset() while True: # making a loop try: # used try so that if user pressed other than the given key error will not be shown key = click.getchar() if key == 'a': # Rotate Left state = controller.step(3) elif key == 'd': state = controller.step(2) elif key == 'w': state = controller.step(0) elif key == 's': state = controller.step(1) elif key == 'z': state = controller.step(5) elif key == 'x': state = controller.step(4) elif key == 'c': state = controller.step(6) elif key == 'v': controller.render() elif key == 'q': controller.close() break elif key == 'r': scene = input("Scene id: ") controller.controller.reset('FloorPlan{}'.format(scene)) else: print("Key not supported! Try a, d, w, s, q, r.") except: print("Key not supported! Try a, d, w, s, q, r.")
def getKeystroke(x, y, lcd): c = click.getchar() if c == 's': clearScreen(lcd) elif c == 'q': exit() elif c == '\x1b[A': y - 1 lcd.set_pixel(x, y, 1) lcd.show() elif c == '\x1b[B': y + 1 lcd.set_pixel(x, y, 1) lcd.show() elif c == '\x1b[C': x + 1 lcd.set_pixel(x, y, 1) lcd.show() elif c == '\x1b"[D"': x - 1 lcd.set_pixel(x, y, 1) lcd.show()
def play(self): initial_node_set = NodeSetExtended.from_nodes_text(self.input) node_set = initial_node_set position = node_set.position empty_spot = node_set.get_empty_spot() distances_by_position_and_empty = {(position, empty_spot): 0} while True: print(node_set.show()) position = node_set.position empty_spot = node_set.get_empty_spot() distance = distances_by_position_and_empty[(position, empty_spot)] print( f"At {position} after {distance} moves, use arrow " f"keys to move empty from {empty_spot}, or r to reset: ") key = click.getchar() if key == 'r': node_set = initial_node_set elif key in self.OFFSETS: offset = self.OFFSETS[key] new_empty_spot = empty_spot.offset(offset) if not node_set.can_move_positions(new_empty_spot, empty_spot): print(f"Cannot move from {empty_spot} to {new_empty_spot}") continue node_set = node_set.move_positions(new_empty_spot, empty_spot) new_position = node_set.position new_distance = distance + 1 existing_distance = distances_by_position_and_empty\ .get((new_position, new_empty_spot)) if existing_distance is None \ or existing_distance > new_distance: distances_by_position_and_empty[ (new_position, new_empty_spot)] = new_distance else: print(f"Unknown key {repr(key)}")
def xdomenu(): """interacts with a simple menu.""" char_to_bin = {'s': 'srmenu', 'j': 'jmenu', 'c': 'clipmenu', 't': 'terminal', 'u': 'urxvt', 'p': 'pomodoro', ' ': 'moveempty'} keybrd = PyKeyboard() k_menu = keybrd.menu_key persistent = False print_menu(persistent) while True: sleep(0.1) stdout.flush() char = getchar() try: cmd = char_to_bin[char] print_flush(cmd) if persistent: sleep(0.2) keybrd.tap_key(k_menu) except KeyError: if char == '\t': persistent = not persistent print_menu(persistent) else: keybrd.tap_key(k_menu)
def etchSketch(): import click from gfxhat import lcd, backlight from random import randint import os print("Etch a Sketch running, use arrow keys to draw, 's' to restart or 'q' to exit...") exit = False x = 64 y = 32 clearScreen() displayText("Etch a Sketch", 40, 54) while(exit != True): keyPressed = click.getchar() if(keyPressed == '\x1b[A'): y = drawPixelUp(x,y) randomLedColor() elif(keyPressed == '\x1b[B'): y = drawPixelDown(x,y) randomLedColor() elif(keyPressed == '\x1b[C'): x = drawPixelRight(x,y) randomLedColor() elif(keyPressed == '\x1b[D'): x = drawPixelLeft(x,y) randomLedColor() elif(keyPressed == 'q' or keyPressed == 'Q'): exit = True clearScreen() clearBacklight() elif(keyPressed == 's' or keyPressed == 'S'): clearScreen() displayText("Etch a Sketch", 40, 54) os.system("cls||clear") print("Etch a Sketch running, use arrow keys to draw, 's' to restart or 'q' to exit...")
def message(self): ips = ', '.join(self.ips) warning = click.style('Warning:', bg='red', fg='white', bold=True) msg = """ {warning} not connected to a VPN The ip addresses in config.ini ({config_ips}) don't match your current ip address which is {current_ip}. If you know you are connected to a VPN, add your current ip to the config.ini file otherwise don't add it. Would you like me to open config.ini in your default editor so you can add {current_ip}? [y/n]""".format(config_ips=ips, current_ip=self.ip, warning=warning) msg = format_paragraphs(msg) click.echo(msg) c = click.getchar() click.echo() if c == 'y': click.edit(filename=Config.user_config) else: click.echo('Config is here: %s' % Config.user_config)
def cli(): """ Menu.""" state = STATES.MAIN while 1: if state == STATES.MAIN: click.echo('Main menu:') click.echo(' s: select image') click.echo(' v: preview image') click.echo(' q: quit') char = click.getchar() if char == 's': state = STATES.SELECT elif char == 'v': state = STATES.VIEW elif char == 'q': state = STATES.QUIT else: click.echo('Invalid input') elif state == STATES.SELECT: click.echo('Select menu:') selected_image = select_image_prompt('b') if selected_image: desktop.set_desktop_background(selected_image) state = STATES.MAIN elif state == STATES.VIEW: click.echo('View menu:') launch_selected_image() state = STATES.MAIN elif state == 'quit': return
def test_getchar_special_key_windows(runner, monkeypatch, special_key_char, key_char): ordered_inputs = [key_char, special_key_char] monkeypatch.setattr(click._termui_impl.msvcrt, 'getwch', lambda: ordered_inputs.pop()) monkeypatch.setattr(click.termui, '_getchar', None) assert click.getchar() == special_key_char + key_char
def devserver(ctx, host, port): s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) errno = s.connect_ex(('127.0.0.1', 8000)) if not errno: click.secho('Error: That port is already in use.'.format(port), fg='red') return if not _check_requirements(ctx.obj['REPO_PATH']): click.secho('requirements.txt changed, need upgrade python packages.'.format(port), fg='yellow') click.echo('Do it now? [y/n]') c = click.getchar() if c == 'y': _install_packages(ctx.obj['PYTHON_PATH'], ctx.obj['REPO_PATH'], ctx.obj['DEBUG']) click.echo('Start server Django server') click.echo('Serving on http://{}:{}/'.format(host, port)) click.echo('Exit Ctrl+C') run_process( [ os.path.join(os.getcwd(), os.path.join(ctx.obj['PYTHON_PATH'], 'bin/python')), os.path.join(os.getcwd(), os.path.join(ctx.obj['REPO_PATH'], 'manage.py')), 'runserver', '{}:{}'.format(host, port) ], debug=ctx.obj['DEBUG'] )
def get_action(self, target): if self.global_action is not None: return self.global_action # Mapping of options to return values mapping = {"s": "skip", "b": "backup", "u": "update (overwrite)"} # Prepare Prompt options = [] for val in mapping.values(): options.append("[{}]{}".format(val[0], val[1:])) options.append("[{}]{} all".format(val[0].upper(), val[1:])) prompt_text = ("File already exists: {}\n" "What do you want to do?\n" "{}").format(target, ", ".join(options)) # Show Prompt click.echo(prompt_text) # Get and validate input action = " " while action.lower() not in mapping: action = click.getchar() click.echo(action) # Set the action val = mapping[action.lower()].split()[0] if action.isupper(): self.global_action = val return val
def webserver(ctx, host, port, htdocs, static, autoreload): s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) errno = s.connect_ex(('127.0.0.1', 8000)) if not errno: click.secho('Error: That port is already in use.'.format(port), fg='red') return if not _check_requirements(ctx.obj['REPO_PATH']): click.secho('requirements.txt changed, need upgrade python packages.'.format(port), fg='yellow') click.echo('Do it now? [y/n]') c = click.getchar() if c == 'y': _install_packages(ctx.obj['PYTHON_PATH'], ctx.obj['REPO_PATH'], ctx.obj['DEBUG']) click.echo('Start server uWSGI') click.echo('Serving on http://{}:{}/'.format(host, port)) click.echo('Exit Ctrl+C') run_process( [ 'uwsgi', '--http', '{}:{}'.format(host, port), '--home', os.path.join(os.getcwd(), ctx.obj['PYTHON_PATH']), '--chdir', os.path.join(os.getcwd(), ctx.obj['REPO_PATH']), '--module', 'app.wsgi', '--processes', '1', '--threads', '2', '--py-autoreload', str(autoreload), '--static-map', '/static={}'.format(os.path.join(os.getcwd(), static)), '--static-map', '/={}'.format(os.path.join(os.getcwd(), htdocs)), '--static-index', 'index.html' ], debug=ctx.obj['DEBUG'] )
def init(ctx, project_name): if os.path.exists(os.path.join(ctx.obj['REPO_PATH'], '.git')): click.echo(click.style('Error: Project already initial.', fg='red')) return if not _check_project(project_name, ctx.obj['username'], ctx.obj['password']): click.echo(click.style('Error: Project does not exists.', fg='red')) return _create_directories() _clone_project(ctx.obj['REPO_PATH'], project_name, ctx.obj['username'], ctx.obj['password'], ctx.obj['DEBUG']) _create_virtualenv(ctx.obj['PYTHON_PATH'], ctx.obj['DEBUG'], ctx.obj['CREATE_ENV']) _install_packages(ctx.obj['PYTHON_PATH'], ctx.obj['REPO_PATH'], ctx.obj['DEBUG'], ctx.obj['CREATE_ENV']) _download_conf(project_name, ctx.obj['username'], ctx.obj['password']) click.echo('Download static files? [y/n]') c = click.getchar() if c == 'y': _download_static(project_name, ctx.obj['username'], ctx.obj['password'], ctx.obj['DEBUG'])
def deploy(nodes_count, hosts_mapping): click.secho("With big nodes_count, this example is DB heavy, it creates NxN connections, continue ? [y/N] ", fg='red', nl=False) c= click.getchar() if c in ('y', 'Y'): setup_riak(nodes_count, hosts_mapping) else: click.echo("Aborted")
def xdomenu(): """Shows a simple menu.""" char_to_bin = {'q': ('xmctl', 'srmenu'), 'j': ('xmctl', 'jmenu'), 'n': ('xmctl', 'nvim'), 'h': ('urxvt', ['-e', 'htop']), 'u': ('urxvt', ['-name', 'urxvt', '-n', 'urxvt']), 'i': ('xmctl', 'ipython'), 'p': ('xmctl', 'perl'), 'r': ('xmctl', 'ranger'), 'a': ('xmctl', 'allpads'), 'b': ('xmctl', 'byobu'), 'P': ('xmctl', 'pomodoro')} echo('Main menu:') echo(' q: qutebrowser') echo(' j: j4-app-menu') echo(' n: neovim') echo(' i: ipython') echo(' p: perl repl') echo(' r: ranger') echo(' a: all pads') echo(' b: byobu') echo(' P: pomodoro') echo(' h: htop') echo(' u: urxvt') char = getchar() cmd = Command(char_to_bin[char][0]) cmd(char_to_bin[char][1])
def cli(input_file, output_file, caption, delimiter, quotechar, display_length, overwrite): """ CSVtoTable commandline utility. """ # Prompt for file overwrite if outfile already exists if not overwrite and os.path.exists(output_file): fmt = "File ({}) already exists. Do you want to overwrite? (y/n): " message = fmt.format(output_file) click.secho(message, nl=False, fg="red") choice = click.getchar() click.echo() if choice not in ("y", "Y"): return True # Convert CSV file convert.convert(input_file, output_file, caption=caption, delimiter=delimiter, quotechar=quotechar, display_length=display_length) click.secho("File converted successfully: {}".format(output_file), fg="green")
def describe_projects(self): page = 1 while True: projects, project_count = self._get_projects( page=page, page_size=self.CURRENT_PAGE_COUNT) table = rich.table.Table(show_header=True, header_style="bold magenta") table.add_column("NAME", width=50) table.add_column("LABELS", justify="right") table.add_column("PROGRESS", justify="right") for item in projects: table.add_row(item.name, f"{item.label_count}", f"{item.progress}%") console.print(table) total_page = math.ceil(project_count / self.CURRENT_PAGE_COUNT) if total_page > page: click.echo( f'Press any button to continue to the next page ({page}/{total_page}). Otherwise press ‘Q’ to quit.', nl=False) key = click.getchar() click.echo() page = page + 1 if key == 'q' or key == 'Q': return elif total_page <= page: return
def _ui_getchar_pick(choices: Sequence[str], prompt: str = 'Select from: ') -> int: ''' Basic menu allowing the user to select one of the choices returns the index the user chose ''' assert len(choices) > 0, 'Didnt receive any choices to prompt!' eprint(prompt + '\n') # prompts like 1,2,3,4,5,6,7,8,9,a,b,c,d,e,f... chr_offset = ord('a') - 10 # dict from key user can press -> resulting index result_map = {} for i, opt in enumerate(choices, 1): char: str = str(i) if i < 10 else chr(i + chr_offset) result_map[char] = i - 1 eprint(f'\t{char}. {opt}') eprint('') while True: ch = click.getchar() if ch not in result_map: eprint(f'{ch} not in {list(result_map.keys())}') continue return result_map[ch]
def _process_next_character(self, old_line: str): """ Get the next character and decide what the new line state should be. Returns: 0. Is it the end of the line? 1. The new line state """ char = click.getchar(echo=False) if char == "\\": new_line = old_line + self._process_backslash_escape() elif len(char) == 1 and char.isprintable(): new_line = old_line + char elif char == "\t": new_line = old_line + " " elif is_backspace(char): new_line = old_line[:-1] else: new_line = old_line backspace(len(old_line)) print(self.highlighter.colorize_source_line(new_line), end="") if char == ENTER: print() return True, new_line else: return False, new_line
def connect_to_workspace(): try: print "[*] Connecting to SpyBot....Make sure the SpyBot is ONLINE!" os.chdir("./YalerTunnel") # dev=open(os.devnull,'wb') print "[*] Starting Yaler Services..." subprocess.Popen( "java YalerTunnel client 127.0.0.1:10022 try.yaler.io:80 gsiot-3jpy-p0d6", shell=True, stdout=dev, stderr=dev) print "[*] Yaler Services Started." os.chdir("../") print "[*] Launching Terminal.." cmd = "\"ssh root@localhost -p 10022 -o ServerAliveInterval=5\"" # cmd2="\"ping google.com\"" #Testing purposes term = "gnome-terminal -e " + cmd + " --geometry=120x25" subprocess.Popen(term, shell=True, stderr=dev, stdout=dev) while True: print "[*] Press 1 to launch another terminal/Retry" print "[*] Press 2 to return to main menu" ch = click.getchar() if ch == '1': print "[*] Launching Terminal.." subprocess.Popen(term, shell=True) elif ch == '2': print "[*] Returning to main menu" break else: print "[*] Enter a valid choice! " continue return except: print "[*] Oops something went wrong when connecting to SpyBot!" return
def parse(self, response): sel = Selector(response) shows = response.xpath('//ul/li') names=dict() for show in shows: name = [s.encode('utf-8') for s in show.xpath('a/text()').extract()] link = show.xpath('a/@href').extract() # use key-value store in order to extract links from series names[str(name).decode('utf-8').strip('[]')] = link # brute force key-value search for items in name for key, value in names.iteritems(): if series in key.strip(): click.secho("\nFound %s" % str(key).strip('[]').encode('utf-8'),bg='green',fg='white') click.echo('Shall we continue? [yn]', nl=False) # make sure that the user recognizes that this is what they want to add to the database # TODO: Make sure that I remove all entries from the DB that match this series so that users can update easily # TODO: Also make sure that it determines what needs to be updated and what doesn't c = click.getchar() click.echo() if c == 'y': click.secho("\nContinued",bg='green',fg='white') elif c == 'n': click.secho("\nTerminated",bg='red',fg='white') break; else: click.secho("\nInvalid Input!",bg='red',fg='white') break; yield scrapy.Request(str(value[0]),meta={ 'root_link' : value, 'name' : str(key).strip('[]\'\'').encode('utf-8')},callback=self.parse_episodes,priority=200) names.clear() break;
def recommend_next_step(self, obs, eps=0.05): key_map = {'q':7, 'w':8, 'e':9, 'a':4, 's':5, 'd':6, 'z':1, 'x':2, 'c':3} exit_map = [3, 22, 24, 26, 27] # Ctrl+C Ctrl+V Ctrl+X Ctrl+Z ESC print("Possible actions: ", obs['possible_actions']) print("press key: ") while True: try: key = click.getchar() if isinstance(key,cabc.ByteString): key = chr(ord(key.decode("ascii"))) if key.lower() in key_map.keys() and key_map[key.lower()] in obs['possible_actions']: action = key_map[key.lower()] break if key.isdigit() and int(key) in obs['possible_actions']: action = int(key) break isexit = ord(key.encode('ascii', 'ignore')) if isexit in exit_map: print("Exit key received. exiting game now.") exit() print("Invalid action! Pick one of the possible actions and try again.") except click.ClickException: print("click exception. exiting game now.") exit() return action
def clean(directory, remove, size): """Quick script to clean up music directories: * Displays improperly formatted directories * Displays directories that are too small to likely have any music (default 2MB). You may specify a different maximum size. """ results = check_dir(directory, size) if not remove: for _, result in results.items(): display(result['label'], result['dirs']) else: display(results['empty']['label'], results['empty']['dirs']) while True: click.secho('Delete directories? [y/n]', bg='red', fg='white', bold=True) response = click.getchar() if response not in ['y', 'n']: click.echo('Warning: Invalid Input') elif response == 'y': for path in results['empty']['dirs']: rmtree(path) break else: break
def executeProgram(): # Generate dictionary charDictionary = generateDictionary() # Define escape variable ESC = '\x1b' # Print info print('Please enter a character (Quit - ESC):') while True: # Get a char from the user c = getchar() # Check for quitting if (c == ESC): break # Get object from dictionary objectList = charDictionary.get(c) # Check object if (objectList == None): print(f'Character {c} is not present in the dictionary') print('Please enter a character (Quit - ESC):') else: setBacklight(True) displayObject(objectList, 5, 5, ignoreOutOfRangeError=False) # End of the program print('End of the program') setBacklight(False) clearScreen(lcd)
def main(self): self.run() return input_help = "`, G, g, i, o, h, Q" log("Input thread started") input_lock = False while True: c = click.getchar() if c == '`': input_lock = not input_lock log("Input Lock? {}".format(input_lock)) else: if input_lock: pass elif c == 'G': self.app.cascade_detector.next_classifier('frontalface') elif c == 'g': self.app.cascade_detector.next_classifier('profileface') elif c == 'i': self.app.input.add_interval(-1) elif c == 'o': self.app.input.add_interval(1) elif c == 'h': log(input_help) elif c == 'Q': log("Exit") exit(0) else: log(c)
def sketch(x, y): while True: inp = getchar() if inp == '\x1b[A': # up y -= 1 if y == 0: y = 63 if inp == '\x1b[B': # down y += 1 if y == 63: y = 0 if inp == '\x1b[C': # right x += 1 if x == 127: x = 0 if inp == '\x1b[D': # left x -= 1 if x == 0: x = 127 if inp == "s": clearScreen(lcd) elif inp == "q": break else: lcd.set_pixel(x, y, 1) lcd.show()
def process_command(c): if c == 1 or c == 2: ate = c == 1 calories = click.prompt('Number of calories', type=int) action = "eat" if ate else "do" note = click.prompt('What did you {}?'.format(action)) create_entry(calories, note, ate) elif c == 3: weight = click.prompt('Enter your new weight', type=int) create_entry(weight) elif c == 4: #TODO: Lookup items via pager pass elif c == 5: click.echo('(F)ood or (E)xercise? ') c = click.getchar().lower() ate = c == 'F' calories = click.prompt('Number of calories', type=int) note = click.prompt('Name this entry') create_entry(calories, note, ate) add_shortcut(calories, note) elif c == 6: show_status() elif c == 7: show_log() elif c == 8: click.edit(filename=bogg_utils.CONFIG_PATH) elif c == 9: return False return True
def run_commands(section_header, commands, skip_last_input=False, comment=None): """Run a list of commands, displaying them within the given section.""" global auto_run for i, command in enumerate(commands): # Display the status. vars = { "section_header": section_header, "total": len(commands), "command": command, "v": i + 1, } click.secho( "\nRunning %(section_header)s %(v)s/%(total)s : %(command)s" % vars, bold=True, ) click.secho("\n%(v)s/%(total)s : %(command)s" % vars, fg="yellow", bold=True) if comment: click.secho(comment) # Run the command. os.system(command) last_command = i + 1 == len(commands) if not (auto_run or (last_command and skip_last_input)): click.secho( "Press [enter] to continue or [a] to continue on auto:\n> ", nl=False ) response = click.getchar() if response == "a": print("Turning on auto run.") auto_run = True
def move(): # Stworzenie nowego publishera pub = rospy.Publisher('/turtle1/cmd_vel', Twist, queue_size=10) # Zainicjowanie wezla rospy.init_node('move') # Pobranie z serwera parametrow odpowiednich liter klawiszy UP = rospy.get_param("up") LEFT = rospy.get_param("left") DOWN = rospy.get_param("down") RIGHT = rospy.get_param("right") # Petla wykonywana, dopoki program dziala while not rospy.is_shutdown(): # Stworzenie obiektu typu Twist - wiadomosci wysylanej przez wezel # zawierajacej wspolrzedne przesuniecia i obrotu twist = Twist() # Uzyskanie informacji o wcisnietym przycisku key_pressed = click.getchar() # Sprawdzenie, ktory przycisk zostal wcisniety i ustawianie # parametrow ruchu if key_pressed == UP: twist.linear.x = 2 elif key_pressed == LEFT: twist.angular.z = 1.04719755119 elif key_pressed == DOWN: twist.linear.x = -2 elif key_pressed == RIGHT: twist.angular.z = -1.04719755119 # Publikowanie wiadomosci o przemieszceniu na topic pub.publish(twist)
def magictype(text, prompt_template='default', speed=1): """Echo each character in ``text`` as keyboard characters are pressed. Characters are echo'd ``speed`` characters at a time. """ echo_prompt(prompt_template) cursor_position = 0 with raw_mode(): while True: char = text[cursor_position:cursor_position + speed] in_char = getchar() if in_char in {ESC, CTRLC}: echo(carriage_return=True) raise click.Abort() elif in_char == BACKSPACE: if cursor_position > 0: echo("\b \b", nl=False) cursor_position -= 1 elif in_char in RETURNS: # Only return at end of command if cursor_position >= len(text): echo("\r", nl=True) break elif in_char == CTRLZ and hasattr(signal, 'SIGTSTP'): # Background process os.kill(0, signal.SIGTSTP) # When doitlive is back in foreground, clear the terminal # and resume where we left off click.clear() echo_prompt(prompt_template) echo(text[:cursor_position], nl=False) else: if cursor_position < len(text): echo(char, nl=False) increment = min([speed, len(text) - cursor_position]) cursor_position += increment
def run_delete_project(project_id, project_ids): """Delete tasks, groups, project and results.""" if not project_ids and not project_id: click.echo("Missing argument") return None elif not project_ids: project_ids = [project_id] click.echo("Projects and all associated data including results " + "with following project ids will be deleted permantly:") for project_id in project_ids: click.echo(project_id) click.echo() click.echo("Continue with deletion? [y/n] ", nl=False) click.echo() c = click.getchar() if c == "y": click.echo("Start deletion") if delete_project.delete_project(project_ids): click.echo("Finished deletions") elif c == "n": click.echo("Abort!") else: click.echo("Invalid input")
def cli(vid, pid, debug): errmsg = 'No MCU with KBoot detected !' if debug > 0: loglevel = [logging.NOTSET, logging.INFO, logging.DEBUG] logging.basicConfig(level=loglevel[debug]) devs = KBOOT.scan_usb_devs(vid, pid) if devs: index = 0 if len(devs) > 1: i = 0 click.echo('') for dev in devs: click.secho(" %d) %s" % (i, dev.getInfo())) i += 1 click.echo('\n Select: ', nl=False) c = click.getchar(True) click.echo('') index = int(c, 10) # Connect KBoot USB device KBOOT.connect_usb(devs[index]) return raise Exception(errmsg)
def view(visualization_path, index_extension): # Guard headless envs from having to import anything large import sys if not os.getenv("DISPLAY") and sys.platform != "darwin": raise click.UsageError( 'Visualization viewing is currently not supported in headless ' 'environments. You can view Visualizations (and Artifacts) at ' 'https://view.qiime2.org, or move the Visualization to an ' 'environment with a display and view it with `qiime tools view`.') import zipfile import qiime2.sdk if index_extension.startswith('.'): index_extension = index_extension[1:] try: visualization = qiime2.sdk.Visualization.load(visualization_path) # TODO: currently a KeyError is raised if a zipped file that is not a # QIIME 2 result is passed. This should be handled better by the framework. except (zipfile.BadZipFile, KeyError, TypeError): raise click.BadParameter( '%s is not a QIIME 2 Visualization. Only QIIME 2 Visualizations ' 'can be viewed.' % visualization_path) index_paths = visualization.get_index_paths(relative=False) if index_extension not in index_paths: raise click.BadParameter( 'No index %s file with is present in the archive. Available index ' 'extensions are: %s' % (index_extension, ', '.join(index_paths.keys()))) else: index_path = index_paths[index_extension] launch_status = click.launch(index_path) if launch_status != 0: click.echo('Viewing visualization failed while attempting to ' 'open %s' % index_path, err=True) else: while True: click.echo( "Press the 'q' key, Control-C, or Control-D to quit. This " "view may no longer be accessible or work correctly after " "quitting.", nl=False) # There is currently a bug in click.getchar where translation # of Control-C and Control-D into KeyboardInterrupt and # EOFError (respectively) does not work on Python 3. The code # here should continue to work as expected when the bug is # fixed in Click. # # https://github.com/pallets/click/issues/583 try: char = click.getchar() click.echo() if char in {'q', '\x03', '\x04'}: break except (KeyboardInterrupt, EOFError): break
def yesno(prompt): click.echo(prompt + " [yN] ", nl=False) c = click.getchar() click.echo(c) if c == "y" or c == "Y": return True else: return False
def changes_confirmation(text): confirm = None while confirm not in ('y', 'n', 's'): click.echo('\n%s [y]es / [n]o / [s]kip all' % text) confirm = click.getchar(echo=True).lower() if 's' == confirm: raise SkipRestException() return 'y' == confirm
def keyboard(self): ''' Should start a new thread. ''' while True: k = click.getchar() self.__last_pressed_key = k print('Key is pressed by another threading')
def pause(info="Press any key to continue ...", err=False): """Same as click.pause but without masking KeyboardError""" if info: click.echo(info, nl=False, err=err) result = click.getchar() if info: click.echo(err=err) return result
def run(self): print("Key listening thread started") # print('Starting ' + self.name) while True: self.last_key_press = click.getchar() if self.last_key_press == 'q': print("Key listening thread terminated") break
def wait_for(chars): while True: in_char = getchar() if in_char == ESC: echo() raise click.Abort() if in_char in chars: echo() return in_char
def loadprint(filename): with open(filename) as f: dat = json.load(f) mylist = [(x, y, z) for x in range(len(dat)) for y in range(5) for z in range(y + 1, 5)] names = ('baseline', 'tranx-annot', 'best-tranx', 'best-tranx-rerank', 'snippet') random.shuffle(mylist) for (i, j, k) in mylist: sname = 'grade-' + names[j] + '-' + names[k] if sname not in dat[i]: click.clear() click.echo( '''Which of the two following snippets is more relevant to the posed problem? Please enter a number from 0 to 2. You can also enter \'f\' to finish rating or \'s\' to skip the problem 1: The first snippet is more relevant 2: The second snippet is more relevant 0: I cannot decide, which snippet is more relevant''') click.echo(' ') click.echo('The problem is:') click.echo(dat[i]['intent']) click.echo(' ') x = random.randint(1, 2) click.echo('The first snippet is:') if x == 1: click.echo(dat[i][names[j]]) if x == 2: click.echo(dat[i][names[k]]) click.echo(' ') click.echo('The second snippet is:') if x == 1: click.echo(dat[i][names[k]]) if x == 2: click.echo(dat[i][names[j]]) click.echo(' ') while True: c = click.getchar() click.echo(c) if c == 'f': break elif c == 's': break elif c in ['0', '1', '2']: if x == 1: dat[i][sname] = int(c) if x == 2: dat[i][sname] = (3 - int(c)) % 3 with open(filename[:-5] + '.tmp.json', 'w') as o: json.dump(dat, o) break else: print("Sorry, the input was invalid") continue if c == 'f': break click.echo('Thank you for grading!') with open(filename, 'w') as o: json.dump(dat, o) try: os.remove(filename[:-5] + '.tmp.json') except: pass
def wait_for(chars): while True: in_char = getchar() if in_char in {ESC, CTRLC}: echo(carriage_return=True) raise click.Abort() if in_char in chars: echo() return in_char
def ask(self, options, key): click.echo(options, nl=False) get = click.getchar() # On Windows, getchar returns a byte string which looks like a bug # https://github.com/pallets/click/issues/537 if Config.is_win: try: get = get.decode('utf-8') except UnicodeDecodeError: # On windows, if a non character key (like an arrow # key) is pressed, there looks like there are two key # press events which causes a second loop through this # function. In the case of a right arrow key, the # second key is an 'M' which would cause an # inadvertent selection if there was an 'M' option. # The non char key causes a UnicodeDecodeError so # we'll stop here. sys.exit('Invalid key') click.echo(get) choice = False key = list(key) if self.table_type == 'download': if get == 'q': # quit sys.exit() elif get == 's': # skip choice = 'skip' elif get == 'r': # skip rest of series choice = 'skip_rest' elif get == 'm': # mark show as watched, but don't download it choice = 'mark' elif self.table_type == 'copy': if get == 'q': sys.exit() elif get == 'a': choice = 'copy_all' elif self.table_type in ['redownload', 'nondb']: if get == 'q': sys.exit() if get in key: # number/letter chosen choice_num = key.index(get) if choice_num not in list(range(len(self.table.body))): self.display_error('Choice not between %s and %s, try again:' % ( key[0], key[len(self.table.body) - 1])) else: choice = self.table.body[choice_num][-1:][0] elif not choice and get not in key: self.display_error('Invalid choice, try again:') return choice
def _wait_input(): """Wait user input.""" if not click.utils.WIN: click.echo('[any]: next\t[q]: quit') if click.getchar() in ['q', u'q', b'q']: sys.exit(0) if not click.utils.WIN: click.echo('\033[F\033[K')
def run(self): """Displays the menu, allowing the user to make selections. """ while self.menus: self.menus[-1].active = True click.clear() self.display() char = click.getchar() self.state = self.state.select(self, self.menus[-1], char)
def magictype(text, prompt_template='default', speed=1): echo_prompt(prompt_template) i = 0 while i < len(text): char = text[i:i + speed] in_char = getchar() if in_char == ESC: echo() raise click.Abort() echo(char, nl=False) i += speed wait_for(RETURNS)
def prompt_guess(): """Get a single letter.""" print_spacer() click.secho('Dare to pick a letter: ', dim=True, bold=True) letter = click.getchar() # \x03 = ctrl+c, \x04 = ctrl+d if letter in ['\x03', '\x04']: raise KeyboardInterrupt return letter
def reset(c7n_async=None): """Delete all persistent cluster state. """ click.echo('Delete db? Are you Sure? [yn] ', nl=False) c = click.getchar() click.echo() if c == 'y': click.echo('Wiping database') worker.connection.flushdb() elif c == 'n': click.echo('Abort!') else: click.echo('Invalid input :(')
def reset(dbpath): """Save the current state to a json file """ click.echo('Delete db? Are you Sure? [yn] ', nl=False) c = click.getchar() click.echo() if c == 'y': click.echo('Wiping database') worker.connection.flushdb() elif c == 'n': click.echo('Abort!') else: click.echo('Invalid input :(')
def confirm(question='Your choice?', default=True, abort_answer=None, allow_abort=True): """Asks a simple question with yes or no answers. Returns True for yes and False for no. default : default answer if user presses return, abort_answer : if True or False, yes / no answer raises Abort; if None, the outcome is returned for both answers. allow_abort : allows aborting by ctrl-C, ctrl-Z or Esc """ # key definitions and their meanings keys = OrderedDict() keys[get_key('y')] = True keys[get_key('n')] = False keys[get_key('esc')] = Abort if allow_abort else False names = {True: 'yes', False: 'no'} default_text, abort_text = '', '' # default and abort answer if default is not None: keys[get_key('enter')] = default default_text = click.style(' Enter = {}'.format(names[default]), fg='yellow') if allow_abort: keys[get_key('esc')] = Abort abort_text = click.style(' Esc = abort', fg='red') # all keys are defined # build answer dict from key getchars answers = {key.getchar: answer for key, answer in keys.items()} # display user prompts click.echo(question) while True: # get the user input click.echo('Choice? [Y/N{}{}]'.format(default_text, abort_text)) getchar = click.getchar() answer = answers.get(getchar) if answer == abort_answer: raise Abort # loop further if answer lookup failed if answer is None: continue # return answer, or raise it (if it was Abort) return dt.try_raising(answer)
def xdomenu(): """interacts with a simple menu.""" xmc = Command('xmctl') char_to_bin = {'q': ('srmenu'), 'c': ('clipmenu'), 'j': ('jmenu'), 'n': ('nvim'), 'h': ('htop'), 'u': ('myterm'), 'i': ('ipython'), 'p': ('perl'), 'r': ('ranger'), 'a': ('allpads'), 'b': ('byobu'), 'P': ('pomodoro')} xdo = Command('xdotool') hinter = EWMH() persistent = False print_menu(persistent) while True: char = getchar() if char == '\t': persistent = not persistent echo("\n") print_menu(persistent) continue elif char == ' ': xdo(['key', 'Menu']) xmc('nextempty') xdo(['key', 'Menu']) continue if persistent: xmc('minone') else: xmc('suicide') if char == 'b': if not class_is_mapped(hinter, 'urxv'): xmc('byobu') sleep(1) else: if class_is_visible(hinter, 'urxv'): xmc('sendbyo') else: xmc('bringbyo') else: (opts) = char_to_bin[char] xmc(opts) if persistent: xdo(['key', 'Menu']) continue raise KeyboardInterrupt
def tools(): """Little tools""" #from converter_helpers import * menu = 'main' while 1: if menu == 'main': click.echo('Main menu:') click.echo(' f: (f)requency converter') click.echo(' w: (w)avelength converter') click.echo(' q: (q)uit') char = click.getchar() if char == 'f': menu = 'freq' elif char == 'w': menu = 'wave' elif char == 'q': return else: click.echo('Invalid input') elif menu == 'freq': echo_frequency_units() char = click.getchar() if char.upper() == 'Q': return else: mult = get_frequency_multiplier(char.upper()) elif menu == 'wave': click.echo('Wavelength converter') click.echo('press any button to continue') char = click.getchar() if char.upper() == 'Q': return else: mult = get_wavelength_multiplier(char.upper()) return
def promptUserToContinue(message=""): ''' Pauses, prints an optional message, and asks the user if they wish to continue. message - string to print to user, optional ''' print message click.echo('Continue? [yn] ', nl=False) c = click.getchar() click.echo() if c == 'y': click.echo('We will go on') else: click.echo('Abort!') quit()
def pause(self, msg1='', msg2='Press any key to continue...', min_verbosity=0, allow_abort=False): """Waits until user presses a key""" if self.verbosity >= min_verbosity: abort_text = '' abort_key_chars = [] if allow_abort: keys = ', '.join(key.name for key in DEFAULT_ABORT_KEYS) abort_text = click.style(' [{}: abort]'.format(keys), fg='cyan') abort_key_chars = [key.getchar for key in DEFAULT_ABORT_KEYS] click.echo('{}\n\t{}{}'.format(msg1, msg2, abort_text)) char = click.getchar() if char in abort_key_chars: raise Abort
def simple_menu(message, options, default_key=None, allow_abort=True): """A simple menu where user is asked what to do. Wrong choice points back to the menu if default_option is not defined. message : string displayed on screen, options : a list of MenuItem namedtuples, default_key : default key for wrong hits, allow_abort : allow aborting with ctrl-C, ctrl-Z and/or Esc. """ # generate a list of valid options valid_options = get_sorted_valid_options(options) # dictionary of key: return value pairs rets = {option.key.getchar: option.value for option in valid_options} # get default return value for wrong keypress if we have default_key # default to some nonsensical string for wrong dict hits # this will make it possible to have None as an option def_key = get_key(default_key) default_retval = rets.get(def_key.getchar, NONSENSE) # check which keys can be used for aborting the menu # pressing one of them would raise Abort, if two conditions are met: # aborting is enabled (allow_abort=True) and key is not in options abort_keys = [key for key in DEFAULT_ABORT_KEYS if allow_abort and key.getchar not in rets] abort_getchars = [key.getchar for key in abort_keys] # abort prompt abort_s = ('[{}: abort]' .format(', '.join(key.name for key in abort_keys)) if abort_keys else '') # add default key combo if it was specified if default_retval == NONSENSE: prompt = 'Your choice? :' else: prompt = 'Your choice? [{}] :'.format(def_key.name) # display the menu entries = (build_entry(o, trailing_newline=0) for o in valid_options) click.echo('\n'.join(['', message, '', *entries, '', abort_s, prompt])) # Wait for user input while True: getchar = click.getchar() if getchar in abort_getchars: raise Abort retval = rets.get(getchar, default_retval) if retval != NONSENSE: return dt.try_raising(retval)
def instance_kill(instance_ids, yes): if not yes: click.echo('Continue? [y|N] ', nl=False) c = click.getchar() click.echo() if c.lower() != 'y': return instances = cloud.instances() for r, inst in instances.items(): for i in inst: if i.id in instance_ids: i.terminate() click.echo('{1:28s} {0:11s} terminated from {2}'.format(i.id, i.name, r))