def _command_psql(self, *, flags: AbstractSet[str], arg: Optional[str]) -> None: pgaddr = self.get_server_pgaddr() if not pgaddr: print('\\psql requires EdgeDB to run in DEV mode') return pg_config = buildmeta.get_pg_config_path() psql = pg_config.parent / 'psql' cmd = [ str(psql), '-h', pgaddr['host'], '-p', str(pgaddr['port']), '-d', self.connection.dbname, '-U', pgaddr['user'] ] def _psql(cmd: List[str]) -> int: proc = subprocess.Popen(cmd) while proc.returncode is None: try: proc.wait() except KeyboardInterrupt: pass return proc.returncode pt_app.run_in_terminal(lambda: _psql(cmd) == 0) self.prompt.app.current_buffer.reset() # Fix 'psql' command stdout artefacts: print('\r ')
def _(event): " Say 'hello' when `c-t` is pressed. " def print_hello(): print('right') sock.mysend(bytes(d['backwardCommand'], 'utf-8')) time.sleep(0.25) run_in_terminal(print_hello)
def color_print(formatted_text: List[Tuple[str, str]], style: Dict[str, str] = None) -> None: """Print colored text leveraging :func:`~prompt_toolkit.shortcuts.print_formatted_text`. This function automatically handles printing the text without interrupting the current prompt. Args: formatted_text: A list of formatted_text. style: Style to apply to `formatted_text` in :class:`dictionary` form. Example: >>> color_print(formatted_text=[("class:aa", "hello "), ("class:bb", "world")], style={"aa": "red", "bb": "blue"}) >>> color_print([("red", "yes"), ("", " "), ("blue", "no")]) """ def _print(): print_formatted_text( FormattedText(formatted_text), style=Style.from_dict(style) if style else None, ) if get_app().is_running: run_in_terminal(_print) else: _print()
def command_psql(self, args): settings = self.connection.get_settings() pgaddr = settings.get('pgaddr') if not pgaddr: print('\\psql requires EdgeDB to run in DEV mode') return host = os.path.dirname(pgaddr) port = pgaddr.rpartition('.')[2] pg_config = buildmeta.get_pg_config_path() psql = pg_config.parent / 'psql' cmd = [ str(psql), '-h', host, '-p', port, '-d', self.connection.dbname, '-U', 'postgres' ] def _psql(cmd): proc = subprocess.Popen(cmd) while proc.returncode is None: try: proc.wait() except KeyboardInterrupt: pass return proc.returncode pt_app.run_in_terminal(lambda: _psql(cmd) == 0) self.prompt.app.current_buffer.reset() print('\r ')
def output_reader(handle, callback, *args, **kwargs): if handle is None: return for line in iter(handle.readline, b""): if not line and line != "": break run_in_terminal(functools.partial(callback, line, *args))
def redo_last_cmd(self, event): def noti(): print("Redo last cmd") if self.last_cmd is not None: self.exec_buffer.append(self.last_cmd) self.proceed_cmd() run_in_terminal(noti)
def save(self, event): def noti(): print("Saved!!") if len(self.exec_buffer) > 0: self.proceed_cmd() self.worksheet.save(self.model_file) run_in_terminal(noti)
def undo_last_cmd(self, event): def noti(): print("Abort last cmd") if len(self.exec_buffer) > 0: self.last_cmd = self.exec_buffer.pop() self.last_cmd.abort() run_in_terminal(noti)
def _(event): """ Copy username of last viewed account to clipboard """ def copyText(): copyTextToClipboard(GlobalVariables.LAST_ACCOUNT_VIEWED_USERNAME, 'user name', 'User name') run_in_terminal(copyText)
def _(event): """ Copy password of last viewed account to clipboard """ def copyText(): copyTextToClipboard(GlobalVariables.LAST_ACCOUNT_VIEWED_PASSWORD, 'password', 'Password') run_in_terminal(copyText)
def _(event): """ Copy URL of last viewed account to clipboard """ def copyText(): copyTextToClipboard(GlobalVariables.LAST_ACCOUNT_VIEWED_URL, 'URL', 'URL') run_in_terminal(copyText)
def _(event): """ Copy comment of last viewed account to clipboard """ def copyText(): copyTextToClipboard(GlobalVariables.LAST_ACCOUNT_VIEWED_COMMENT, 'comment', 'Comment') run_in_terminal(copyText)
def _(event: KeyPressEvent): buffer = event.current_buffer def do_forward(): cmd_name = "forward" buffer.insert_text(cmd_name) buffer.validate_and_handle() run_in_terminal(do_forward)
def _(event): """ Copy email of last viewed account to clipboard """ def copyText(): copyTextToClipboard(GlobalVariables.LAST_ACCOUNT_VIEWED_EMAIL, 'email', 'Email') run_in_terminal(copyText)
async def parse_command_line(self, text): if not await self.switched_context(text): try: command = shlex.split(text) logging.debug( f"command: {command[0]} args: {command[1:]} ctx: {self.current_context.name}" ) needs_patch, command = self.patch_badchar(command) args = docopt(getattr( self.current_context if hasattr(self.current_context, command[0]) else self, command[0]).__doc__, argv=command[1:]) if needs_patch: args = self.patch_badchar(args, patch=True) except ValueError as e: print_bad(f"Error parsing command: {e}") except AttributeError as e: print_bad(f"Unknown command '{command[0]}'") except (DocoptExit, SystemExit): pass else: if command[ 0] in self._cmd_registry or self.current_context._remote is False: run_in_terminal( functools.partial(getattr( self if command[0] in self._cmd_registry else self.current_context, command[0]), args=args)) elif self.current_context._remote is True: logging.info( f"{self.current_context.name}, {command[0]}, args : {args}" ) response = await self.teamservers.send( ctx=self.current_context.name, cmd=command[0], args=args) logging.info(f"response: {response.result}") if response.status == 'success' and response.result: if hasattr(self.current_context, command[0]): run_in_terminal( functools.partial(getattr( self.current_context, command[0]), args=args, response=response)) elif response.status == 'error': print_bad(response.result) if self.current_context.name != 'main': await self.update_prompt(self.current_context)
def _(event: KeyPressEvent): buffer = event.current_buffer def do_next(): cmd_name = "next" buffer.insert_text(cmd_name) Command.from_raw_input(cmd_name) buffer.validate_and_handle() run_in_terminal(do_next)
def _(event): """ Print 'hello world' in the terminal when ControlT is pressed. We use ``run_in_terminal``, because that ensures that the prompt is hidden right before ``print_hello`` gets executed and it's drawn again after it. (Otherwise this would destroy the output.) """ def print_hello(): print('hello world') run_in_terminal(print_hello)
def _(event): """ Print 'hello world' in the terminal when ControlT is pressed. We use ``run_in_terminal``, because that ensures that the prompt is hidden right before ``print_hello`` gets executed and it's drawn again after it. (Otherwise this would destroy the output.) """ def print_hello(): print('hello world') run_in_terminal(print_hello)
def buffer_list(editor): """ List all buffers. """ def handler(): wa = editor.window_arrangement for info in wa.list_open_buffers(): char = '%' if info.is_active else '' eb = info.editor_buffer print(' %3i %-2s %-20s line %i' % ( info.index, char, eb.location, (eb.buffer.document.cursor_position_row + 1))) six.moves.input('\nPress ENTER to continue...') run_in_terminal(handler)
def buffer_list(editor): """ List all buffers. """ def handler(): wa = editor.window_arrangement for info in wa.list_open_buffers(): char = '%' if info.is_active else '' eb = info.editor_buffer print(' %3i %-2s %-20s line %i' % ( info.index, char, eb.location, (eb.buffer.document.cursor_position_row + 1))) six.moves.input('\nPress ENTER to continue...') run_in_terminal(handler)
def _(event): """ Open URL in web browser """ def openUrl(): if GlobalVariables.LAST_ACCOUNT_VIEWED_URL == "" or GlobalVariables.LAST_ACCOUNT_VIEWED_URL == "-": print("Can not open empty URL.") return print("Opening URL '%s'..." % GlobalVariables.LAST_ACCOUNT_VIEWED_URL) webbrowser.open_new_tab(GlobalVariables.LAST_ACCOUNT_VIEWED_URL) run_in_terminal(openUrl)
def _playlist_binding(event: Any) -> None: # pylint: disable=unused-argument def playlist() -> None: """List songs""" media_player = player.get_media_player() media = media_player.get_media() media.parse() current_artist = media.get_meta(vlc.Meta.Artist) current_album = media.get_meta(vlc.Meta.Album) current_title = media.get_meta(vlc.Meta.Title) print_playlist(tracks, current_artist=current_artist, current_album=current_album, current_title=current_title) run_in_terminal(playlist)
def parse_result(self, result): if len(result): if not self.switched_context(result): command = split(result) try: logging.debug(f"command: {command[0]} args: {command[1:]} ctx: {self.current_context.name}") bound_cmd_handler = functools.partial(getattr(self.current_context, command[0]), args=command[1:]) run_in_terminal(bound_cmd_handler) except AttributeError: print_bad(f"Unknown command '{command[0]}'") if args['--debug']: traceback.print_exc() except DocoptExit as e: print(str(e)) except SystemExit: pass
def patched_print(*values) -> None: """Patched :func:`print` that can print values without interrupting the prompt. See Also: :func:`print` :func:`~prompt_toolkit.application.run_in_terminal` Args: *values: Refer to :func:`print`. Examples: >>> patched_print("Hello World") """ def _print(): print(*values) run_in_terminal(_print)
def parse_result(self, result): if len(result): if not self.context_switching(result): command = split(result) try: bound_cmd_handler = functools.partial(getattr( self.current_context, command[0]), args=command[1:]) run_in_terminal(bound_cmd_handler) except TypeError: print(f"Error type") except AttributeError as ae: print(f"Error with the command '{command[0]}':\n{ae}") except DocoptExit as e: print(str(e)) except SystemExit: pass
def parse_result(self, result): if len(result): if not self.switched_context(result): command = split(result) try: logging.debug(f"command: {command[0]} args: {command[1:]} ctx: {self.current_context.name}") bound_cmd_handler = functools.partial(getattr(self.current_context, command[0]), args=command[1:]) run_in_terminal(bound_cmd_handler) except AttributeError: print_bad(f"Unknown command '{command[0]}'") if args['--debug']: traceback.print_exc() except DocoptExit as e: print(str(e)) except SystemExit: pass
def _(event: KeyPressEvent) -> None: try: list( reader.read_str( event.current_buffer.text, resolver=runtime.resolve_alias, eof=_eof, )) except reader.UnexpectedEOFError: event.current_buffer.insert_text("\n") except reader.SyntaxError as e: run_in_terminal( partial( traceback.print_exception, reader.SyntaxError, e, e.__traceback__, )) else: event.current_buffer.validate_and_handle()
def execute_command(buff): """Send command to subprocess dealing with dry argument recursively""" dry = False if buff.text.lower() in ['n', 'no', 'false'] else True dry_flag = 'DRY' if dry else 'NOT DRY' dry_string = 'n' if dry else '' command = "rsync -avucP{} {} {}".format(dry_string, self.source_field.text, self.target_field.text) def run_script(): subprocess.call(command, shell=True) def print_info(): print_formatted_text( HTML('<ansired>{} </ansired>'.format(dry_flag))) print_formatted_text( HTML('<ansired>{} </ansired>'.format( 'You entered: {}'.format(command)))) print_formatted_text( HTML('<ansired>{} </ansired>'.format('Running...'))) run_in_terminal(print_info) if dry: run_in_terminal(run_script) return else: con = db_connect() create_rsync_record(con, self.source_field.text, self.target_field.text) run_in_terminal(run_script) app = get_app() app.exit() return
async def data_handler(self): #self.connected.set_result(True) async for data in self.ws: data = json.loads(data) if data['type'] == "message": logging.debug(f'Got message from server: {data}') await self.msg_queue.put(data) elif data['type'] == 'event': logging.debug(f'Got event from server: {data}') try: event_handler = functools.partial(getattr( self.event_handlers, data['name'].lower()), data=data['data']) with patch_stdout(): run_in_terminal(event_handler) #run_in_executor=True ? except AttributeError: logging.error( f"Got event of unknown type '{data['name']}'") self.stats.CONNECTED = False logging.debug("data_handler has stopped")
async def data_handler(self): async for data in self.ws: data = json.loads(data) if data['type'] == "message": await self.msg_queue.put(data) elif data['type'] == 'event': try: event_handler = functools.partial(getattr( self.event_handlers, data['name'].lower()), data=data['data']) with patch_stdout(): run_in_terminal(event_handler) except AttributeError: logging.error( f"status: Got event of unknown type '{data['name']}'") self.stats.CONNECTED = False logging.debug("data_handler has stopped")
def serve(self, client): logging.debug(f"connection accepted from {self.listener.last_accepted}") while True: try: data = client.recv() except EOFError: pass topic, msg = data logging.debug(f"Got event: {topic} msg: {msg}") if topic in self.subscribers: for sub in self.subscribers[topic]: future = run_in_terminal(functools.partial(sub, msg)) future.add_done_callback(functools.partial(lambda f, c: c.send(f.result()), c=client)) else: logging.debug(f"Got event: {topic}, but there's nothing subscribed")
def _play_binding(event: Any) -> None: # pylint: disable=unused-argument def play() -> None: """Play song""" player.play() run_in_terminal(play)
def _help(event: Any) -> None: # pylint: disable=unused-argument def _print_help() -> None: print_help() run_in_terminal(_print_help) get_app().invalidate()
def _playlist_binding(event): def playlist(): """List songs""" for s in songs: print(s) run_in_terminal(playlist)
def _play_binding(event): def play(): """Play song""" player.play() run_in_terminal(play)