async def connect_to_aircraft(): session = PromptSession() # text = await prompt_async('TGCS> How many aircraft?: ', key_bindings=bindings) with patch_stdout(): result = await session.prompt_async('TGCS> How many aircraft?: ') # text = await prompt_async('TGCS> Serial (1) or IP (2)', key_bindings=bindings) with patch_stdout(): result = await session.prompt_async('TGCS> Serial (1) or IP (2)') if text == '1': if sys.platform == "darwin": serialport = "/dev/tty.usbmodem1" else: serial_list = mavutil.auto_detect_serial(preferred_list=[ '*FTDI*', "*Arduino_Mega_2560*", "*3D_Robotics*", "*USB_to_UART*", '*PX4*', '*FMU*', "*Gumstix*" ]) if len(serial_list) == 0: print("Error: no serial connsection found") return if len(serial_list) > 1: print('Auto-detected serial ports are:') for port in serial_list: print(" {:}".format(port)) print('Using port {:}'.format(serial_list[0])) serialport = serial_list[0].device drone = Craft('drone0', 'serial://' + serialport + ':57600') if text == '2': drone = Craft('drone0', 'udp://:14540') drone.start() return drone
def __help(): with patch_stdout(): print("") print("Available Commands and Uses\n") for k, v in COMMANDS.items(): with patch_stdout(): print('{} : {}'.format(k, v)) with patch_stdout(): print("")
def run(self): """Run the prompt until user termination. Prompt exits on KeyboardInterrupt or EOF. """ from prompt_toolkit import PromptSession from prompt_toolkit.patch_stdout import patch_stdout from prompt_toolkit.completion import WordCompleter prompt_completer = WordCompleter(self.commands.keys()) if self.custom_psession: psession = self.custom_psession else: psession = PromptSession(completer=prompt_completer, reserve_space_for_menu=3) try: while True: with patch_stdout(): rawin = psession.prompt(self.pstr) # prompt(self.pstr) self.handleCommand(rawin) except (KeyboardInterrupt, EOFError): # Catch Ctrl-C, Ctrl-D, and exit. print("User interrupt.") finally: # Cleanup pass
async def prompt(self, message) -> t.Awaitable[str]: with patch_stdout(): return await self.prompt_session.prompt_async( message, # completer=self.completer, refresh_interval=0.5, )
async def read_and_send(wsconn): session = PromptSession() while True: with patch_stdout(): result = await session.prompt_async('> ') # print('> %s' % result) await wsconn.send(result)
async def main(server): with patch_stdout(): try: await interactive_shell(server) finally: pass warning("Bye Bye!!!")
async def cmd_prompt(prompt_sess, ws): while True: with patch_stdout(): result = await prompt_sess.prompt_async() if not result.startswith('.'): await send_command(ws, result) elif result in (".q", ".quit"): print("Bye.") pending = asyncio.all_tasks() for t in pending: t.cancel() # TODO: less workaroundy #elif result == ".stop": # https://craftserve.pl/s/{server_id}/switch # Body: STOP # elif result == ".start": # https://craftserve.pl/s/{server_id}/switch # Body: START # .expires: expiration date listing # .wallet: wallet balance get # .getaddr: getting all associated domain names # .setname: domain name setting # big amount of data on https://craftserve.pl/s/{server_id}/?json=1 else: print("Unknown csrv-cli command!")
def main(): if args.setup: os.system( 'openssl req -nodes -x509 -newkey rsa:4096 -keyout key.pem -out cert.pem -days 365' ) print("key.pem and cert.pem created") return load_target("*") httpd = HTTPServer((args.address, args.port), C2) if args.ssl: httpd.socket = ssl.wrap_socket(httpd.socket, keyfile=args.keyfile, certfile=args.certfile, server_side=True) srv_thread = threading.Thread(target=httpd.serve_forever, args=()) srv_thread.daemon = True srv_thread.start() print("HTTP Server running on port {}".format(args.port)) print("{}help for more help".format(cmd_escape)) session = PromptSession() while True: try: with patch_stdout(): cmd = session.prompt("{}>".format(target)) cmd = prepare(cmd) if cmd: tasks[target].put(cmd) print("Command queued for {}".format(target)) #print(tasks) except Exception as e: print(e)
def go(): global ALIVE hrm = threading.Thread(target=slowly_send_spam) hrm.start() with patch_stdout(): while ALIVE: try: line = prompt(PROMPT) except KeyboardInterrupt: print("from you: ^C break") break except EOFError: print("from you: EOF") break if line.lower().strip() in ("exit", "stop", "quit"): print("from you:", line, "(quitting)") break if line and line.strip(): print("from you:", line) print("exited loop, waiting for spam thread join") ALIVE = False hrm.join()
async def run(self): prompt = self._build_cli() self._status_bar.start() try: while True: try: with patch_stdout(): text = await prompt.prompt_async( PygmentsTokens(self._get_prompt_tokens()), rprompt=PygmentsTokens( self._status_bar.get_rprompt_tokens() ), ) session_logger = self._plugin.get_session_logger(self._ctx) if session_logger: # Commands don't get written to stdout, so we have to # explicitly dump them to the session log. session_logger.log_command(text) with session_logger.patch(): await self.parse_and_evaluate(text) else: await self.parse_and_evaluate(text) except KeyboardInterrupt: pass except EOFError: # Application exiting. pass self._status_bar.stop()
def main(): doc = """ Mesh CLI Usage: meshcli [options] [<command>] meshcli -h | --help | --version Options: -l --login <login> User login to platform service (email) -p --password <password> User password to platform service (!unsecured!) -n --project <project> Project name to be loaded from platform --partner <partner> Partner identifier [default: silvair] --env <environment> Environment: dev,preprod or prod [default: preprod] -d --debug -h --help Show this help message and exit --version Show version and exit """ use_asyncio_event_loop() arguments = docopt(doc, version="stat_checker 0.5") logging.basicConfig( format= "%(asctime)s %(name)-40s %(levelname)-8s %(filename)15s:%(lineno)3s %(message)s", level=logging.INFO, datefmt="%Y-%m-%d %H:%M:%S", ) loop = asyncio.get_event_loop() mesh_cli = MeshCommandLine(loop, arguments) with suppress(EOFError, KeyboardInterrupt), patch_stdout(): loop.run_until_complete(mesh_cli.run(arguments.get("<command>")))
def main(): # Tell prompt_toolkit to use the asyncio event loop. use_asyncio_event_loop() with patch_stdout(): shell_task = asyncio.ensure_future(interactive_shell()) loop.run_until_complete(shell_task) print('Quitting event loop. Bye.')
async def onJoin(self, details): print('Connected!') self._ticks = 0 def onevent(tick_nb): self._ticks += 1 await self.subscribe(onevent, 'com.example.tick') #validator = AsyncNumberValidator(self) validator = NumberValidator() print(validator) # The patch_stdout() context manager is optional, but it’s recommended, # because other coroutines could print to stdout. This ensures that other # output won’t destroy the prompt. with patch_stdout(): # we are waiting for user input now - but without blocking! # that is, eg the above event handler will continue to receive events while # the user is still not finished with input x = await prompt('x: ', validator=validator, async_=True) # user input is validated (in above, against a number validator) - but the value is # still returned as string, and hence needs to be converted x = int(x) y = self._ticks res = await self.call('com.example.add2', x, y) print("RPC succeded: {} + {} = {}".format(x, y, res)) self.leave()
def repl(parser_factory, *, prompt='> ', multiline=False, style=None, validate_while_typing=True, validate=True, prompt_continuation=': ', uses_pygments_tokens=False, prints_result=True, prints_exceptions=True): """A read-eval-print loop for pyparsing-highlighting examples.""" def prompt_continuation_fn(*args, **kwargs): return prompt_continuation parser = parser_factory(dummy_styler) pph = PPHighlighter(parser_factory, uses_pygments_tokens=uses_pygments_tokens) ppv = PPValidator(parser, multiline=multiline) if validate else None history = InMemoryHistory() session = PromptSession(prompt, multiline=multiline, lexer=pph, validate_while_typing=validate_while_typing, validator=ppv, style=style, history=history, prompt_continuation=prompt_continuation_fn) while True: try: with patch_stdout(): s = session.prompt() result = parser.parseString(s, parseAll=True) if prints_result: for item in result: print(repr(item)) except ParseBaseException as err: if prints_exceptions: print('{}: {}'.format(type(err).__name__, err), file=sys.stderr) except KeyboardInterrupt: pass except EOFError: break
def _do_shell(args): print_info(f'bunga {__version__}') client = ClientThread(args.uri, ShellClient) client.start() with patch_stdout(): shell_main(client)
def main(): bottom_toolbar = HTML( ' <b>[f]</b> Print "f" <b>[q]</b> Abort <b>[x]</b> Send Control-C.') # Create custom key bindings first. kb = KeyBindings() cancel = [False] @kb.add("f") def _(event): print("You pressed `f`.") @kb.add("q") def _(event): " Quit by setting cancel flag. " cancel[0] = True @kb.add("x") def _(event): " Quit by sending SIGINT to the main thread. " os.kill(os.getpid(), signal.SIGINT) # Use `patch_stdout`, to make sure that prints go above the # application. with patch_stdout(): with ProgressBar(key_bindings=kb, bottom_toolbar=bottom_toolbar) as pb: for i in pb(range(800)): time.sleep(0.01) if cancel[0]: break
def main(): bottom_toolbar = HTML(' <b>[f]</b> Print "f" <b>[q]</b> Abort <b>[x]</b> Send Control-C.') # Create custom key bindings first. kb = KeyBindings() cancel = [False] @kb.add('f') def _(event): print('You pressed `f`.') @kb.add('q') def _(event): " Quit by setting cancel flag. " cancel[0] = True @kb.add('x') def _(event): " Quit by sending SIGINT to the main thread. " os.kill(os.getpid(), signal.SIGINT) # Use `patch_stdout`, to make sure that prints go above the # application. with patch_stdout(): with ProgressBar(key_bindings=kb, bottom_toolbar=bottom_toolbar) as pb: for i in pb(range(800)): time.sleep(.01) if cancel[0]: break
def main(network, no_dns, f_interface): # Tell prompt_toolkit to use the asyncio event loop. try: with patch_stdout(): loop = asyncio.get_event_loop() use_asyncio_event_loop() interface = netcheck.get_netdevice( network.split('/')[0]) # cut off cidr netmask if not interface: if f_interface: interface = f_interface else: raise Exception( 'Can not continue without interface. Try to specify using "-i" argument' ) print('interface is %s' % interface) # SETUP SHELL # add hostnames add completer hosts_d = { ip: hostname for ip, hostname in netcheck.get_hostnames( network, filter_hosts=not no_dns) } whosonline_completer.words += list(hosts_d.values()) # start shell shell_task = asyncio.ensure_future( interactive_shell(loop, network, hosts_d, interface, no_dns)) loop.run_until_complete(shell_task) except Exception as e: print(e)
def run(self): self._thread.start() self._bot_status_monitor.start() with patch_stdout(raw=True): while True: # Get our text try: text = self.prompt(rprompt=self._get_rprompt_tokens) # KeyboardInterrupt continues except KeyboardInterrupt: continue # End of file returns except EOFError: return # Clean text text = text.lstrip() # Handle empty text if text == '': self._logger.debug(' empty string found') continue # Program specific handeling. Currently either first word # or second word can be commands for string in text.split('&&'): self._handle_text(string)
async def producer_handler(cphrsuit, websocket, username, chatroom, servaddr): try: footelem = HTML("<b>[" + chatroom + "]</b>" + " <b>" + username.strip() + "</b> > End-to-end encryption enabled on '" + servaddr + "' - Hit Ctrl+C to EXIT") while True: with patch_stdout(): mesgtext = await sess.prompt_async( lambda: "[" + obtntime() + "] " + formusnm(str(username) ) + " > ", bottom_toolbar=footelem, validator=emtyfind(), refresh_interval=0.5, prompt_continuation=lambda width, line_number, is_soft_wrap: " " * width) if mesgtext.strip() == "/list": senddata = mesgtext.strip() else: senddata = json.dumps({ "username": username.strip(), "chatroom": chatroom, "mesgtext": mesgtext.strip() }) senddata = cphrsuit.encrjson(senddata) await websocket.send(senddata) except EOFError: raise KeyboardInterrupt
def prompt_for_code(self): if self.rl_next_input: default = self.rl_next_input self.rl_next_input = None else: default = '' # In order to make sure that asyncio code written in the # interactive shell doesn't interfere with the prompt, we run the # prompt in a different event loop. # If we don't do this, people could spawn coroutine with a # while/true inside which will freeze the prompt. policy = asyncio.get_event_loop_policy() old_loop = get_asyncio_loop() # FIXME: prompt_toolkit is using the deprecated `asyncio.get_event_loop` # to get the current event loop. # This will probably be replaced by an attribute or input argument, # at which point we can stop calling the soon-to-be-deprecated `set_event_loop` here. if old_loop is not self.pt_loop: policy.set_event_loop(self.pt_loop) try: with patch_stdout(raw=True): text = self.pt_app.prompt(default=default, **self._extra_prompt_options()) finally: # Restore the original event loop. if old_loop is not None and old_loop is not self.pt_loop: policy.set_event_loop(old_loop) return text
async def read_input(self): """ Coroutine reading the user's keyboard input and transforming it into the CMessage. If '//exit' is read here, the program exits. """ use_asyncio_event_loop() while True: with patch_stdout(): message = await prompt( f'> {self.name}({self.address}:{self.port}): ', async_=True) if message == '//exit': logging.info(f'{self.logical_clock}: Exiting...') self.exiting = True if self.next_node_writer is not None: self.next_node_writer.close() await self.next_node_writer.wait_closed() return umsg = self.craft_message(MessageType.user_message, message) await self.send_user_message(umsg)
async def my_coroutine(): session = PromptSession() while True: with patch_stdout(): result = await session.prompt_async('Say something: ') print("< [" + str(time.ctime()) + "] " + str(result)) await notify_mesej(result)
async def UaeDebugger(uaedbg): history = InMemoryHistory() session = PromptSession('(debug) ', history=history) with patch_stdout(): try: lines = await uaedbg.recv() while lines is not None: for line in lines: print(line) try: cmd = '' while not cmd: cmd = await session.prompt_async() cmd.strip() uaedbg.send(cmd) except EOFError: uaedbg.resume() except KeyboardInterrupt: uaedbg.kill() lines = await uaedbg.recv() except asyncio.CancelledError: pass except EOFError: pass except Exception as ex: print('Debugger bug!') print('Quitting...')
def teamserver(self): """ The main cmdloop logic that handles navigation to other menus. """ session = PromptSession(complete_in_thread=True, bottom_toolbar=self.bottom_toolbar, refresh_interval=5) while True: try: with patch_stdout(raw=True): text = session.prompt('Server > ', refresh_interval=None) print(helpers.color('[!] Type exit to quit')) except KeyboardInterrupt: print(helpers.color("[!] Type exit to quit")) continue # Control-C pressed. Try again. except EOFError: break # Control-D pressed. if text == 'exit': choice = input(helpers.color("[>] Exit? [y/N] ", "red")) if choice.lower() == "y": self.shutdown() return True else: pass
def launch(self): colorama.init() use_asyncio_event_loop() patch_stdout() while self.run_again: self.run_again = False self._loop = True self.loop.create_task(self.start()) try: self.loop.run_until_complete( self.app.run_async().to_asyncio_future()) except KeyboardInterrupt: if self.current_ip != self.own_ip: self.loop.run_until_complete(self.command("dc"))
def main(path, command, process_and_exit, horizontal, manual, focus): if len(path) > 1: raise click.ClickException("Only one path argument is supported") if process_and_exit and manual: raise click.ClickException("--manual with --process-and-exit makes no sense") ctx = context.get() path = path[0] if path else None if path or not sys.stdin.isatty(): if path: with open(path) as f: text = f.read() else: text = sys.stdin.read() sys.stdin.close() sys.stdin = open(2) ctx.input_buffer.text = text ctx.live = not manual ctx.box_veritcal_orientation = not horizontal ctx.cmd_buffer.text = command if process_and_exit: ctx.non_interactive = True process_one() else: ctx.app = create_app(focus) with patch_stdout(): ctx.app.run() if ctx.print_output_on_exit or ctx.non_interactive: print(ctx.output_buffer.text)
async def prompt(): # @bindings.add('c-c') # async def _(event): # print("\n\n\n\n") # print("Good Bye!, may your props be intact") # event.app.exit() global loop loop = True print("Welcome!") session = PromptSession() drones = 'serial' while loop == True: print_main_page() with patch_stdout(): text = await session.prompt_async('TGCS> ' ) #, key_bindings=bindings) # text = await prompt_async('TGCS> ', key_bindings=bindings) if text == '1': drones = connect_to_aircraft() if text == '2': await actions(drones, session) if text == '3': status(drones) if text == '4': settings() os.system('clear')
def prompt_for_code(self): if self.rl_next_input: default = self.rl_next_input self.rl_next_input = None else: default = '' # In order to make sure that asyncio code written in the # interactive shell doesn't interfere with the prompt, we run the # prompt in a different event loop. # If we don't do this, people could spawn coroutine with a # while/true inside which will freeze the prompt. try: old_loop = asyncio.get_event_loop() except RuntimeError: # This happens when the user used `asyncio.run()`. old_loop = None asyncio.set_event_loop(self.pt_loop) try: with patch_stdout(raw=True): text = self.pt_app.prompt(default=default, **self._extra_prompt_options()) finally: # Restore the original event loop. asyncio.set_event_loop(old_loop) return text
async def main(): with patch_stdout(): background_task = asyncio.create_task(print_counter()) try: await interactive_shell() finally: background_task.cancel() print("Quitting event loop. Bye.")
async def _main(): await init() with patch_stdout(): try: await interactive_shell() finally: print("caught") print("Quitting event loop. Bye.")
def main(): with patch_stdout(): shell_task = asyncio.ensure_future(interactive_shell()) background_task = asyncio.gather(print_counter(), return_exceptions=True) loop.run_until_complete(shell_task) background_task.cancel() loop.run_until_complete(background_task) print('Quitting event loop. Bye.')
def prompt_for_code(self): if self.next_input: default = self.next_input self.next_input = None else: default = '' with patch_stdout(raw=True): text = self.pt_cli.prompt( default=default, # pre_run=self.pre_prompt,# reset_current_buffer=True, ) return text
def prompt_for_code(self): if self.rl_next_input: default = self.rl_next_input self.rl_next_input = None else: default = '' with patch_stdout(raw=True): text = self.pt_app.prompt( default=default, # pre_run=self.pre_prompt,# reset_current_buffer=True, **self._extra_prompt_options()) return text
def get_completions(self, document, complete_event): if not document.current_line.strip(): return # Some bits of our completion system may print stuff (e.g. if a module # is imported). This context manager ensures that doesn't interfere with # the prompt. with patch_stdout(), provisionalcompleter(): body = document.text cursor_row = document.cursor_position_row cursor_col = document.cursor_position_col cursor_position = document.cursor_position offset = cursor_to_position(body, cursor_row, cursor_col) yield from self._get_completions(body, offset, cursor_position, self.ipy_completer)
async def prompt(self, text=None): ''' Prompt for user input from stdin. ''' if self.sess is None: hist = FileHistory(s_common.getSynPath('cmdr_history')) self.sess = PromptSession(history=hist) if text is None: text = self.cmdprompt with patch_stdout(): retn = await self.sess.prompt(text, async_=True, vi_mode=self.vi_mode, enable_open_in_editor=True) return retn
def main(): # Create user interface. hello_world_window() # Enable threading in GTK. (Otherwise, GTK will keep the GIL.) gtk.gdk.threads_init() # Read input from the command line, using an event loop with this hook. # We use `patch_stdout`, because clicking the button will print something; # and that should print nicely 'above' the input line. with patch_stdout(): session = PromptSession('Python >>> ', inputhook=inputhook, lexer=PygmentsLexer(PythonLexer)) result = session.prompt() print('You said: %s' % result)
def cmdloop(self): """ Interprets commands read from stdin until a shutdown is requested or EOF encountered. """ completer = Completer(self._get_all_commands()) try: while True: if os.isatty(sys.stdin.fileno()): with patch_stdout(): cmd = self._session.prompt(self.prompt, completer=completer, style=self.prompt_style) else: cmd = input(self.prompt) self.onecmd(cmd) except EOFError: pass
def main(): # Print a counter every second in another thread. running = True def thread(): i = 0 while running: i += 1 print('i=%i' % i) time.sleep(1) t = threading.Thread(target=thread) t.daemon = True t.start() # Now read the input. The print statements of the other thread # should not disturb anything. with patch_stdout(): result = prompt('Say something: ') print('You said: %s' % result) # Stop thread. running = False