Esempio n. 1
0
 def __init__(self, host):
     self.host = host
     self.socket = None
     self.cli = CommandLineInterface(
         application=create_prompt_application('> '),
         eventloop=create_asyncio_eventloop())
     sys.stdout = self.cli.stdout_proxy()
Esempio n. 2
0
async def td_client_interactive_shell(callback):
    eventloop = create_asyncio_eventloop()

    key_bindings_manager = KeyBindingManager.for_prompt()
    load_td_client_kay_bindings(key_bindings_manager=key_bindings_manager)

    cli = CommandLineInterface(
        application=create_prompt_application('待开发指令,just echo: ',
                                              key_bindings_registry=key_bindings_manager.registry,
                                              get_bottom_toolbar_tokens=get_td_client_bottom_toolbar_tokens,
                                              style=get_td_client_styles()
                                              ),
        eventloop=eventloop
    )

    sys.stdout = cli.stdout_proxy()

    while True:
        try:
            result = await cli.run_async()
            if callback is not None:
                resp = callback(user_input=result.text)
                print(resp)
            else:
                print('You said: "{0}"'.format(result.text))
        except (EOFError, KeyboardInterrupt):
            return
def interactive_shell():
    """
    Coroutine that shows the interactive command line.
    """
    # Create an asyncio `EventLoop` object. This is a wrapper around the
    # asyncio loop that can be passed into prompt_toolkit.
    eventloop = create_asyncio_eventloop()

    # Create interface.
    cli = CommandLineInterface(application=create_default_application(
        'Say something inside the event loop: '),
                               eventloop=eventloop)

    # Patch stdout in something that will always print *above* the prompt when
    # something is written to stdout.
    sys.stdout = cli.stdout_proxy()

    # Run echo loop. Read text from stdin, and reply it back.
    while True:
        try:
            result = yield from cli.run_async()
            print('You said: "%s"\n' % result.text)
        except (EOFError, KeyboardInterrupt):
            loop.stop()
            print('Qutting event loop. Bye.')
            return
def interactive_shell():
    """
    Coroutine that shows the interactive command line.
    """
    # Create an asyncio `EventLoop` object. This is a wrapper around the
    # asyncio loop that can be passed into prompt_toolkit.
    eventloop = create_asyncio_eventloop()

    # Create interface.
    cli = CommandLineInterface(
        application=create_default_application('Say something inside the event loop: '),
        eventloop=eventloop)

    # Patch stdout in something that will always print *above* the prompt when
    # something is written to stdout.
    sys.stdout = cli.stdout_proxy()

    # Run echo loop. Read text from stdin, and reply it back.
    while True:
        try:
            result = yield from cli.run_async()
            print('You said: "%s"\n' % result.text)
        except (EOFError, KeyboardInterrupt):
            loop.stop()
            print('Qutting event loop. Bye.')
            return
Esempio n. 5
0
    async def connected(self):
        # prompt_toolkit internally checks if it's on windows during output rendering but
        # we need to force that we use Vt100_Output not Win32_Output
        from prompt_toolkit import renderer
        renderer.is_windows = lambda: False

        def get_size():
            return self._size

        self._cli = CommandLineInterface(
            application=create_prompt_application(self._shell.prompt),
            eventloop=UnstoppableEventLoop(create_asyncio_eventloop(self._loop)),
            input=PatchedStdinInput(sys.stdin),
            output=Vt100_Output(self, get_size))

        self._cb = self._cli.create_eventloop_callbacks()
        self._inputstream = InputStream(self._cb.feed_key)
        # Taken from prompt_toolkit telnet server
        # https://github.com/jonathanslenders/python-prompt-toolkit/blob/99fa7fae61c9b4ed9767ead3b4f9b1318cfa875d/prompt_toolkit/contrib/telnet/server.py#L165
        self._cli._is_running = True

        if self._shell.welcome_message is not None:
            self.send(self._shell.welcome_message.encode())

        self._cli._redraw()
Esempio n. 6
0
    def connected(self):
        # prompt_toolkit internally checks if it's on windows during output rendering but
        # we need to force that we use Vt100_Output not Win32_Output
        from prompt_toolkit import renderer
        renderer.is_windows = lambda: False

        def get_size():
            return self._size

        self._cli = CommandLineInterface(
            application=create_prompt_application(self._shell.prompt),
            eventloop=UnstoppableEventLoop(create_asyncio_eventloop(
                self._loop)),
            input=PatchedStdinInput(sys.stdin),
            output=Vt100_Output(self, get_size))

        self._cb = self._cli.create_eventloop_callbacks()
        self._inputstream = InputStream(self._cb.feed_key)
        # Taken from prompt_toolkit telnet server
        # https://github.com/jonathanslenders/python-prompt-toolkit/blob/99fa7fae61c9b4ed9767ead3b4f9b1318cfa875d/prompt_toolkit/contrib/telnet/server.py#L165
        self._cli._is_running = True

        if self._shell.welcome_message is not None:
            self.send(self._shell.welcome_message.encode())

        self._cli._redraw()
Esempio n. 7
0
async def interactive_shell():
    """
    Like `interactive_shell`, but doing things manual.
    """
    # Create an asyncio `EventLoop` object. This is a wrapper around the
    # asyncio loop that can be passed into prompt_toolkit.
    eventloop = create_asyncio_eventloop()

    # Create interface.
    cli = CommandLineInterface(
        application=create_prompt_application('Say something inside the event loop: '),
        eventloop=eventloop
    )

    # Patch stdout in something that will always print *above* the prompt when
    # something is written to stdout.
    sys.stdout = cli.stdout_proxy()

    # Run echo loop. Read text from stdin, and reply it back.
    while True:
        try:
            result = await cli.run_async()
            print('You said: "{0}"'.format(result.text))
        except (EOFError, KeyboardInterrupt):
            return
Esempio n. 8
0
def main(args=sys.argv[1:]):
    parser, args = parseargs(args)

    if args.debug:
        log.setLevel(logging.DEBUG)

    loop = asyncio.get_event_loop()
    grbl = SerialGrbl(args.device, args.baudrate, loop)

    registry = load_key_bindings_for_prompt()
    history = InMemoryHistory()

    app_loop = create_asyncio_eventloop(loop=loop)
    app = create_prompt_application(message='> ',
                                    history=history,
                                    key_bindings_registry=registry)
    cli = CommandLineInterface(application=app, eventloop=app_loop)

    for key, func in key_to_func.items():
        func = functools.partial(func, grbl=grbl, loop=loop)
        registry.add_binding(key, eager=True)(func)

    try:
        main_task = asyncio.ensure_future(main_coro(loop, grbl, cli))
        return loop.run_until_complete(main_task)
    except (EOFError, KeyboardInterrupt):
        main_task.cancel()
        return 1
    except serial.SerialException as error:
        log.fatal(error)
        return 1
Esempio n. 9
0
    def __init__(self, base_dir, config):
        for module in config.get('modules'):
            import_module(module)

        self.tasks = TaskManager(self)
        self.window = MainWindow(self)
        self.style = ToshStyle(config.get('ui', 'style'))
        self._parser = CommandLineParser(self, base_dir)
        self.config = config
        self.variables = {}

        application = Application(
            layout=self.window,
            buffer=Buffer(
                enable_history_search=True,
                complete_while_typing=False,
                is_multiline=False,
                history=FileHistory(base_dir + "/history"),
                # validator=validator,
                completer=CommandLineCompleter(self),
                auto_suggest=AutoSuggestFromHistory(),
                accept_action=AcceptAction(self.run_command),
            ),
            mouse_support=config.get('ui', 'mouse'),
            style=self.style,
            key_bindings_registry=get_key_bindings(self),
            use_alternate_screen=True)

        self._cli = CommandLineInterface(application=application,
                                         eventloop=create_asyncio_eventloop(),
                                         output=create_output(true_color=True))
Esempio n. 10
0
 def __init__(self, name=None):
     ptk_loop = create_asyncio_eventloop()
     self.loop = ptk_loop.loop
     self.cli = self._get_cli(ptk_loop)
     sys.stdout = self.cli.stdout_proxy(raw=True)
     super().__init__(name=name)
     self._prompt = PROMPT
     self._prompt_more = PROMPT_MORE
     self._multi_line = False
     self._exit_on_next_kb_interrupt = False
Esempio n. 11
0
def embed(globals=None,
          locals=None,
          vi_mode=False,
          history_filename=None,
          no_colors=False,
          startup_paths=None,
          patch_stdout=False,
          return_asyncio_coroutine=False):
    """
    Call this to embed  Python shell at the current point in your program.
    It's similar to `IPython.embed` and `bpython.embed`. ::

        from prompt_toolkit.contrib.repl import embed
        embed(globals(), locals(), vi_mode=False)

    :param vi_mode: Boolean. Use Vi instead of Emacs key bindings.
    """
    globals = globals or {}
    locals = locals or globals

    def get_globals():
        return globals

    def get_locals():
        return locals

    # Create eventloop.
    if return_asyncio_coroutine:
        eventloop = create_asyncio_eventloop()
    else:
        eventloop = create_eventloop()

    # Create REPL.
    repl = PythonRepl(eventloop,
                      get_globals,
                      get_locals,
                      vi_mode=vi_mode,
                      history_filename=history_filename,
                      style=(None if no_colors else PythonStyle))

    # Start repl.
    patch_context = repl.cli.patch_stdout_context(
    ) if patch_stdout else DummyContext()

    if return_asyncio_coroutine:

        def coroutine():
            with patch_context:
                for future in repl.asyncio_start_repl():
                    yield future

        return coroutine()
    else:
        with patch_context:
            repl.start_repl(startup_paths=startup_paths)
Esempio n. 12
0
 def __init__(self):
     application = Application(
         buffers=self.buffers,
         layout=self.layout,
         key_bindings_registry=self.manager.registry,
         mouse_support=True,
         use_alternate_screen=True,
     )
     eventloop = create_asyncio_eventloop()
     self.cli = CommandLineInterface(application=application,
                                     eventloop=eventloop)
     sys.stdout = self.cli.stdout_proxy()
Esempio n. 13
0
def main():
    loop = asyncio.get_event_loop()
    try:
        coro = loop.create_connection(Client, '192.168.1.2', 9999)
        loop.run_until_complete(coro)
        asyncio. async (client_talk(create_asyncio_eventloop(loop), coro))
    except ConnectionRefusedError:
        sys.stderr.write("Error connecting.\nQuitting.\n")
        return
    try:
        loop.run_forever()
    except KeyboardInterrupt:
        pass
    loop.close()
Esempio n. 14
0
 def run_async(self):
     ''' Runs the user interface as an async task. '''
     eventloop = create_asyncio_eventloop()
     self.cli = CommandLineInterface(application=self.application,
                                     eventloop=eventloop)
     self.cli.focus(COMMAND_BUFFER)
     try:
         while True:
             result = yield from self.cli.run_async()
             if result is None:
                 print('Exiting...')
                 return
     except (EOFError, KeyboardInterrupt):
         return
     finally:
         eventloop.close()
Esempio n. 15
0
    def __init__(self, get_globals, get_locals=None):
        assert callable(get_globals)
        assert get_locals is None or callable(get_locals)

        self._chan = None

        def _globals():
            data = get_globals()
            data.setdefault('print', self._print)
            return data

        repl = PythonRepl(get_globals=_globals,
                          get_locals=get_locals or _globals)

        # Disable open-in-editor and system prompt. Because it would run and
        # display these commands on the server side, rather than in the SSH
        # client.
        repl.enable_open_in_editor = False
        repl.enable_system_bindings = False

        # PipInput object, for sending input in the CLI.
        # (This is something that we can use in the prompt_toolkit event loop,
        # but still write date in manually.)
        self._input_pipe = PipeInput()

        # Output object. Don't render to the real stdout, but write everything
        # in the SSH channel.
        class Stdout(object):

            def write(s, data):
                if self._chan is not None:
                    self._chan.write(data.replace('\n', '\r\n'))

            def flush(s):
                pass

        # Create command line interface.
        self.cli = CommandLineInterface(
            application=repl.create_application(),
            eventloop=create_asyncio_eventloop(),
            input=self._input_pipe,
            output=Vt100_Output(Stdout(), self._get_size))

        self._callbacks = self.cli.create_eventloop_callbacks()
Esempio n. 16
0
    def __init__(self, get_globals, get_locals=None):
        assert callable(get_globals)
        assert get_locals is None or callable(get_locals)

        self._chan = None

        def _globals():
            data = get_globals()
            data.setdefault('print', self._print)
            return data

        repl = PythonRepl(get_globals=_globals,
                          get_locals=get_locals or _globals)

        # Disable open-in-editor and system prompt. Because it would run and
        # display these commands on the server side, rather than in the SSH
        # client.
        repl.enable_open_in_editor = False
        repl.enable_system_bindings = False

        # PipInput object, for sending input in the CLI.
        # (This is something that we can use in the prompt_toolkit event loop,
        # but still write date in manually.)
        self._input_pipe = PipeInput()

        # Output object. Don't render to the real stdout, but write everything
        # in the SSH channel.
        class Stdout(object):
            def write(s, data):
                if self._chan is not None:
                    self._chan.write(data.replace('\n', '\r\n'))

            def flush(s):
                pass

        # Create command line interface.
        self.cli = CommandLineInterface(application=repl.create_application(),
                                        eventloop=create_asyncio_eventloop(),
                                        input=self._input_pipe,
                                        output=Vt100_Output(
                                            Stdout(), self._get_size))

        self._callbacks = self.cli.create_eventloop_callbacks()
Esempio n. 17
0
def embed(globals=None, locals=None, vi_mode=False, history_filename=None, no_colors=False,
          startup_paths=None, patch_stdout=False, return_asyncio_coroutine=False):
    """
    Call this to embed  Python shell at the current point in your program.
    It's similar to `IPython.embed` and `bpython.embed`. ::

        from prompt_toolkit.contrib.repl import embed
        embed(globals(), locals(), vi_mode=False)

    :param vi_mode: Boolean. Use Vi instead of Emacs key bindings.
    """
    globals = globals or {}
    locals = locals or globals

    def get_globals():
        return globals

    def get_locals():
        return locals

    # Create eventloop.
    if return_asyncio_coroutine:
        eventloop = create_asyncio_eventloop()
    else:
        eventloop = create_eventloop()

    # Create REPL.
    repl = PythonRepl(eventloop, get_globals, get_locals, vi_mode=vi_mode,
                      history_filename=history_filename,
                      style=(None if no_colors else PythonStyle))

    # Start repl.
    patch_context = repl.cli.patch_stdout_context() if patch_stdout else DummyContext()

    if return_asyncio_coroutine:
        def coroutine():
            with patch_context:
                for future in repl.asyncio_start_repl():
                    yield future
        return coroutine()
    else:
        with patch_context:
            repl.start_repl(startup_paths=startup_paths)
Esempio n. 18
0
def main():
    # Create an asynchronous event loop.
    loop = asyncio.get_event_loop()

    try:
        # We are creating a coroutine - a tcp client
        couroutine = loop.create_connection(Client, 'localhost', 9999)
        loop.run_until_complete(couroutine)

        # setting a future allows you to declare something that hasn't been called yet.
        # So we set a client which will get called down the line, but not yet.
        asyncio.ensure_future(client_talk(create_asyncio_eventloop(loop)))
    except ConnectionRefusedError:
        sys.stderr.write("Error connecting.\nQuitting.\n")
        return

    try:
        loop.run_forever()  # Now run forever except for a keyboard interrupt.
    except KeyboardInterrupt:
        pass
    loop.close()  # Then close the event loop when done.
Esempio n. 19
0
    def __init__(self, repository, eventloop, tests, config, em, runner_class):
        self.repository = repository
        self.history = InMemoryHistory()
        self.tests = tests
        self.config = config
        self.displayer = TestDisplayer(self.tests)
        self.eventloop = eventloop
        self.runner_class = runner_class
        self.em = em

        # Register the callbacks
        self.em.register(self.displayer.parse_message)

        self.application = create_prompt_application("> ",
                                                     history=self.history,
                                                     completer=completer)

        self.cli = CommandLineInterface(
            application=self.application,
            eventloop=create_asyncio_eventloop(eventloop))

        sys.stdout = self.cli.stdout_proxy()
    def __init__(self, style):
        self._commands = {}
        for d in dir(self.__class__):
            if d.startswith('do_'):
                name = d[3:]
                func = getattr(self, d)
                doc = textwrap.dedent(func.__doc__ or '')
                self._commands[name] = (func, doc)

        self._history = InMemoryHistory()

        self._application = create_prompt_application(
            get_prompt_tokens=self.get_prompt_tokens,
            style=style,
            on_abort=AbortAction.RETURN_NONE,
            history=self._history)

        self._cli = CommandLineInterface(application=self._application,
                                         output=create_output(true_color=True),
                                         eventloop=create_asyncio_eventloop())

        self._style = style
Esempio n. 21
0
async def interactive_shell(bot):
    eventloop = create_asyncio_eventloop(bot.loop)
    cli = CommandLineInterface(
        application=create_prompt_application(':> ',
                                              completer=myCompleter(bot)),
        eventloop=eventloop,
    )

    sys.stdout = cli.stdout_proxy()
    while True:
        try:
            result = await cli.run_async()
            if result.text.startswith("#"):
                parse = total.parseString(result.text[1:], parseAll=True)
                try:
                    resp = await bot.run_parse(parse, Message(server='SHELL'))
                    for res in resp:
                        print(res.text)
                except PipeError as e:
                    for loc, err in sorted(e.exs, key=lambda x: x[0]):
                        if isinstance(err, PipeError):
                            for loc2, err2 in sorted(err.exs,
                                                     key=lambda x: x[0]):
                                try:
                                    raise err2
                                except Exception:  # how to print to terminal
                                    traceback.print_exc()
                        else:
                            try:
                                raise err
                            except Exception:  # how to print to terminal
                                traceback.print_exc()
            else:
                try:
                    await aexec(result.text, local={'bot': bot})
                except Exception:
                    traceback.print_exc()
        except (EOFError, KeyboardInterrupt):
            bot.loop.stop()
Esempio n. 22
0
async def interactive_shell():
    """
    Like `interactive_shell`, but doing things manual.
    """
    # Create an asyncio `EventLoop` object. This is a wrapper around the
    # asyncio loop that can be passed into prompt_toolkit.
    eventloop = create_asyncio_eventloop()

    # Create interface.
    cli = CommandLineInterface(application=create_prompt_application(
        'Say something inside the event loop: '),
                               eventloop=eventloop)

    # Patch stdout in something that will always print *above* the prompt when
    # something is written to stdout.
    sys.stdout = cli.stdout_proxy()

    # Run echo loop. Read text from stdin, and reply it back.
    while True:
        try:
            result = await cli.run_async()
            print('You said: "{0}"'.format(result.text))
        except (EOFError, KeyboardInterrupt):
            return
Esempio n. 23
0
def embed(globals=None, locals=None, configure=None,
          vi_mode=False, history_filename=None, title=None,
          startup_paths=None, patch_stdout=False, return_asyncio_coroutine=False):
    """
    Call this to embed  Python shell at the current point in your program.
    It's similar to `IPython.embed` and `bpython.embed`. ::

        from prompt_toolkit.contrib.repl import embed
        embed(globals(), locals())

    :param vi_mode: Boolean. Use Vi instead of Emacs key bindings.
    :param configure: Callable that will be called with the `PythonRepl` as a first
                      argument, to trigger configuration.
    :param title: Title to be displayed in the terminal titlebar. (None or string.)
    """
    assert configure is None or callable(configure)

    # Default globals/locals
    if globals is None:
        globals = {
            '__name__': '__main__',
            '__package__': None,
            '__doc__': None,
            '__builtins__': six.moves.builtins,
        }

    locals = locals or globals

    def get_globals():
        return globals

    def get_locals():
        return locals

    # Create eventloop.
    if return_asyncio_coroutine:
        eventloop = create_asyncio_eventloop()
    else:
        eventloop = create_eventloop()

    # Create REPL.
    repl = PythonRepl(get_globals, get_locals, vi_mode=vi_mode,
                      history_filename=history_filename,
                      startup_paths=startup_paths)

    if title:
        repl.terminal_title = title

    if configure:
        configure(repl)

    cli = PythonCommandLineInterface(python_input=repl, eventloop=eventloop)

    # Start repl.
    patch_context = cli.patch_stdout_context() if patch_stdout else DummyContext()

    if return_asyncio_coroutine:
        def coroutine():
            with patch_context:
                for future in cli.run_async():
                    yield future
        return coroutine()
    else:
        with patch_context:
            cli.run()
Esempio n. 24
0
            # This can be done another way in bulk, but it is easier to send them one and display it in terminal
            # on the client side, instead of having the client responsible for formatting the display.
            for c in contacts:
                self.send("{}".format(c))
        
# ===============================================================================

if __name__ == '__main__':
    print("{0:s} [SERVER]: starting.".format(tstamp()))

    loop = asyncio.get_event_loop()

    # Creates the asychronous server, is a generic base class of asynchio
    coroutine = loop.create_server(Server, 'localhost', 9999)
    
    server = loop.run_until_complete(coroutine)

    # If this is kinda confusing look up what "futures" are in python
    # This creates a "future" coroutine for the console. It hasn't been created yet though.
    asyncio.ensure_future(server_console(create_asyncio_eventloop(loop)))

    for socket in server.sockets:
        # Just printing the address and port that it is running on.
        print("{0:s} [SERVER]: running on {1:}".format(tstamp(), socket.getsockname()))

    try:
        loop.run_forever()       # Now run forever, lest you get a keyboard interrupt (ctrl+c)
    except KeyboardInterrupt:
        loop.close()
        print("Bye bye.")
Esempio n. 25
0
    Window(content=BufferControl(buffer_name=ASYNC_BUFFER)),
])

buffers={
    DEFAULT_BUFFER: Buffer(is_multiline=True),
    ASYNC_BUFFER: Buffer(is_multiline=True),
}


@registry.add_binding(Keys.ControlC, eager=True)
def key_close(event):
    event.cli.set_return_value(KILL_APP)


eventloop = create_asyncio_eventloop()
application = Application(buffers=buffers,
                          key_bindings_registry=registry,
                          layout=layout,
                          use_alternate_screen=True)
cli = CommandLineInterface(
    application=application,
    eventloop=eventloop)


WARHAMMER_QUOTES = ['A good soldier obeys without question. A good officer commands without doubt.',
'Blessed is the mind too small for doubt.',
'To admit defeat is to blaspheme against the Emperor.',
'For those who seek perfection there can be no rest on this side of the grave.',
'The difference between heresy and treachery is ignorance.',
'Knowledge is power, guard it well.',
Esempio n. 26
0
File: xc.py Progetto: jbg/xc
async def xmpp_client():
  try:
    with open(os.path.join(os.getenv("HOME"), ".xc.conf"), "r") as config_file:
      config = json.load(config_file)
    if "jid" not in config:
      raise Exception("No JID")
  except Exception as e:
    print("Error reading configuration file.\n" + str(e) + "Please create ~/.xc.conf with content like:\n{\"jid\": \"[email protected]\"}")
    sys.exit(1)

  async def get_secret(jid, attempt):
    if attempt > 2:
      return None
    try:
      return await prompt_async("Secret (will not be stored): ", is_password=True)
    except:
      return None

  async def tls_handshake_callback(verifier):
    print("Warning: blindly accepting TLS certificate from %s" % verifier.transport.get_extra_info("server_hostname"))
    return True

  pin_store = PublicKeyPinStore()
  pin_store.import_from_json(config.get("pkps", {}))
  my_jid = aioxmpp.JID.fromstr(config["jid"])
  security = aioxmpp.make_security_layer(get_secret, pin_store=pin_store, pin_type=PinType.PUBLIC_KEY, post_handshake_deferred_failure=tls_handshake_callback)
  client = aioxmpp.PresenceManagedClient(my_jid, security)
  presence = client.summon(aioxmpp.presence.Service)
  roster = client.summon(aioxmpp.roster.Service)

  class RosterItemAndCommandCompleter(Completer):
    def get_completions(self, document, complete_event):
      text = document.text
      if not text or " " in text or ":" in text:
        return
      if text[0] == "/":
        part = text[1:]
        for command in ("roster", "name", "add", "del", "help", "quit"):
          if command.startswith(part):
            yield Completion(command + " ", start_position=-len(part), display=command)
      elif roster is not None:
        for item in roster.items.values():
          if item.name.startswith(text):
            yield Completion(item.name + ": ", start_position=-len(text), display=item.name)

  completer = RosterItemAndCommandCompleter()
  history = InMemoryHistory()

  next_recipient = None
  def get_prompt_tokens(_):
    return ((Token.Prompt, "%s> " % (next_recipient or "")),)

  cli_app = create_prompt_application(get_prompt_tokens=get_prompt_tokens,
                                      completer=completer,
                                      reserve_space_for_menu=0,
                                      history=history,
                                      get_title=lambda: "xc")
  cli_loop = create_asyncio_eventloop()
  cli = CommandLineInterface(application=cli_app, eventloop=cli_loop)
  above_prompt = cli.stdout_proxy()

  def name_for_jid(jid):
    try:
      return roster.items[jid].name
    except:
      return str(jid)

  def peer_available(jid, presence):
    above_prompt.write("%s is now online\n" % name_for_jid(jid.bare()))
  presence.on_available.connect(peer_available)

  def peer_unavailable(jid, presence):
    above_prompt.write("%s is now offline\n" % name_for_jid(jid.bare()))
  presence.on_unavailable.connect(peer_unavailable)

  def message_received(msg):
    content = " ".join(msg.body.values())
    if content:
      above_prompt.write("%s: %s\n" % (name_for_jid(msg.from_.bare()), content))
  client.stream.register_message_callback("chat", None, message_received)

  try:
    async with client.connected() as stream:
      while True:
        try:
          document = await cli.run_async()
        except (KeyboardInterrupt, EOFError):
          break
        line = document.text
        if line.startswith("/"):
          try:
            command, *args = line[1:].split(" ")
            if command == "roster":
              rows = [(item.name, str(jid), item.subscription) for jid, item in roster.items.items() if jid != my_jid]
              widths = [max(len(row[i] or "") for row in rows) for i in range(len(rows[0] or ""))]
              for row in rows:
                above_prompt.write("   ".join((cell or "").ljust(widths[i]) for i, cell in enumerate(row)) + "\n")
            elif command == "name":
              try:
                jid = args[0]
                name = args[1]
              except IndexError:
                above_prompt.write("usage: /name JID NAME\n")
              else:
                jid = aioxmpp.JID.fromstr(jid)
                await roster.set_entry(jid, name=name)
            elif command == "add":
              try:
                jid = args[0]
              except IndexError:
                above_prompt.write("usage: /add JID\n")
              else:
                jid = aioxmpp.JID.fromstr(jid)
                await roster.set_entry(jid)
                roster.subscribe(jid)
                roster.approve(jid)
            elif command == "del":
              try:
                jid = args[0]
              except IndexError:
                above_prompt.write("usage: /del JID\n")
              else:
                jid = aioxmpp.JID.fromstr(jid)
                await roster.remove_entry(jid)
            elif command == "quit":
              break
            elif command == "help":
              above_prompt.write("NAME: MESSAGE    send MESSAGE to NAME\n"
                                 "MESSAGE          send MESSAGE to the last correspondent\n"
                                 "/roster          print the roster\n"
                                 "/add JID         add JID to the roster\n"
                                 "/del JID         remove JID from the roster\n"
                                 "/name JID NAME   set the name of JID to NAME\n"
                                 "/quit            disconnect and then quit (also ctrl-d, ctrl-c)\n"
                                 "/help            this help\n")
            else:
              above_prompt.write("unrecognised command\n")
          except Exception as e:
            above_prompt.write("exception handling command: %s\n" % e)
        else:
          try:
            try:
              recipient, message = line.split(": ", 1)
            except ValueError:
              if next_recipient is not None:
                recipient = next_recipient
                message = line
              else:
                above_prompt.write("recipient: message\n")
                continue
            jid_for_name = lambda r: next((jid for jid, item in roster.items.items() if item.name == r), None)
            jid = jid_for_name(recipient)
            if jid is None:
              if next_recipient is not None and recipient != next_recipient:
                recipient = next_recipient
                jid = jid_for_name(recipient)
                message = line
            if jid is None:
              above_prompt.write("unknown recipient: %s\n" % recipient)
              continue
            msg = aioxmpp.Message(to=jid, type_="chat")
            msg.body[None] = message
            await stream.send_and_wait_for_sent(msg)
            next_recipient = recipient
          except Exception as e:
            above_prompt.write("exception sending message: %s\n" % e)

    print("Disconnecting…")
    client.stop()
  except Exception as e:
    print("Failed to connect: %s" % e)
Esempio n. 27
0
    def prompt(self, message="", **kwargs):
        """Get input from the user and return it.

        This is a wrapper around a lot of prompt_toolkit functionality and
        can be a replacement for raw_input. (or GNU readline.) If you want
        to keep your history across several calls, create one
        `~prompt_toolkit.history.History instance and pass it every
        time. This function accepts many keyword arguments. Except for the
        following. they are a proxy to the arguments of
        create_prompt_application().

        Parameters
        ----------
        patch_stdout : file-like, optional
            Replace ``sys.stdout`` by a proxy that ensures that print
            statements from other threads won't destroy the prompt. (They
            will be printed above the prompt instead.)
        return_asyncio_coroutine : bool, optional
            When True, return a asyncio coroutine. (Python >3.3)

        Notes
        -----
        This method was forked from the mainline prompt-toolkit repo.
        Copyright (c) 2014, Jonathan Slenders, All rights reserved.
        """
        patch_stdout = kwargs.pop("patch_stdout", False)
        return_asyncio_coroutine = kwargs.pop("return_asyncio_coroutine",
                                              False)
        if return_asyncio_coroutine:
            eventloop = create_asyncio_eventloop()
        else:
            eventloop = kwargs.pop("eventloop", None) or create_eventloop()

        # Create CommandLineInterface.
        if self.cli is None:
            if builtins.__xonsh_env__.get("VI_MODE"):
                editing_mode = EditingMode.VI
            else:
                editing_mode = EditingMode.EMACS
            kwargs["editing_mode"] = editing_mode
            cli = CommandLineInterface(
                application=create_prompt_application(message, **kwargs),
                eventloop=eventloop,
                output=create_output(),
            )
            self.cli = cli
        else:
            cli = self.cli

        # Replace stdout.
        patch_context = cli.patch_stdout_context(
        ) if patch_stdout else DummyContext()

        # Read input and return it.
        if return_asyncio_coroutine:
            # Create an asyncio coroutine and call it.
            exec_context = {"patch_context": patch_context, "cli": cli}
            exec(
                textwrap.dedent("""
            import asyncio
            @asyncio.coroutine
            def prompt_coro():
                with patch_context:
                    document = yield from cli.run_async(reset_current_buffer=False)
                    if document:
                        return document.text
            """),
                exec_context,
            )
            return exec_context["prompt_coro"]()
        else:
            # Note: We pass `reset_current_buffer=False`, because that way
            # it's easy to give DEFAULT_BUFFER a default value, without it
            # getting erased. We don't have to reset anyway, because this is
            # the first and only time that this CommandLineInterface will run.
            try:
                with patch_context:
                    document = cli.run(reset_current_buffer=False)
                    if document:
                        return document.text
            except Exception:
                xt.print_exception()
                # return something to prevent xonsh crash when any
                # exceptions raise
                return ""
            finally:
                eventloop.close()
Esempio n. 28
0
    def prompt(self, message="", **kwargs):
        """Get input from the user and return it.

        This is a wrapper around a lot of prompt_toolkit functionality and
        can be a replacement for raw_input. (or GNU readline.) If you want
        to keep your history across several calls, create one
        `~prompt_toolkit.history.History instance and pass it every
        time. This function accepts many keyword arguments. Except for the
        following. they are a proxy to the arguments of
        create_prompt_application().

        Parameters
        ----------
        patch_stdout : file-like, optional
            Replace ``sys.stdout`` by a proxy that ensures that print
            statements from other threads won't destroy the prompt. (They
            will be printed above the prompt instead.)
        return_asyncio_coroutine : bool, optional
            When True, return a asyncio coroutine. (Python >3.3)

        Notes
        -----
        This method was forked from the mainline prompt-toolkit repo.
        Copyright (c) 2014, Jonathan Slenders, All rights reserved.
        """
        patch_stdout = kwargs.pop("patch_stdout", False)
        return_asyncio_coroutine = kwargs.pop("return_asyncio_coroutine", False)
        if return_asyncio_coroutine:
            eventloop = create_asyncio_eventloop()
        else:
            eventloop = kwargs.pop("eventloop", None) or create_eventloop()

        # Create CommandLineInterface.
        if self.cli is None:
            if builtins.__xonsh__.env.get("VI_MODE"):
                editing_mode = EditingMode.VI
            else:
                editing_mode = EditingMode.EMACS
            kwargs["editing_mode"] = editing_mode
            cli = CommandLineInterface(
                application=create_prompt_application(message, **kwargs),
                eventloop=eventloop,
                output=create_output(),
            )
            self.cli = cli
        else:
            cli = self.cli

        # Replace stdout.
        patch_context = cli.patch_stdout_context() if patch_stdout else DummyContext()

        # Read input and return it.
        if return_asyncio_coroutine:
            # Create an asyncio coroutine and call it.
            exec_context = {"patch_context": patch_context, "cli": cli}
            exec(
                textwrap.dedent(
                    """
            import asyncio
            @asyncio.coroutine
            def prompt_coro():
                with patch_context:
                    document = yield from cli.run_async(reset_current_buffer=False)
                    if document:
                        return document.text
            """
                ),
                exec_context,
            )
            return exec_context["prompt_coro"]()
        else:
            # Note: We pass `reset_current_buffer=False`, because that way
            # it's easy to give DEFAULT_BUFFER a default value, without it
            # getting erased. We don't have to reset anyway, because this is
            # the first and only time that this CommandLineInterface will run.
            try:
                with patch_context:
                    document = cli.run(reset_current_buffer=False)
                    if document:
                        return document.text
            except Exception:
                xt.print_exception()
                # return something to prevent xonsh crash when any
                # exceptions raise
                return ""
            finally:
                eventloop.close()
Esempio n. 29
0
    def __init__(self, looper, tmpdir, nodeReg, cliNodeReg, debug=False,
                 logFileName=None):
        self.curClientPort = None
        logging.root.addHandler(CliHandler(self.out))

        self.looper = looper
        self.tmpdir = tmpdir
        self.nodeReg = nodeReg
        self.cliNodeReg = cliNodeReg

        # Used to store created clients
        self.clients = {}  # clientId -> Client
        # To store the created requests
        self.requests = {}
        # To store the nodes created
        self.nodes = {}

        self.cliCmds = {'status', 'new'}
        self.nodeCmds = self.cliCmds | {'keyshare'}
        self.helpablesCommands = self.cliCmds | self.nodeCmds
        self.simpleCmds = {'status', 'exit', 'quit', 'license'}
        self.commands = {'list', 'help'} | self.simpleCmds
        self.cliActions = {'send', 'show'}
        self.commands.update(self.cliCmds)
        self.commands.update(self.nodeCmds)
        self.node_or_cli = ['node',  'client']
        self.nodeNames = list(self.nodeReg.keys()) + ["all"]
        self.debug = debug
        self.plugins = []
        '''
        examples:
        status

        new node Alpha
        new node all
        new client Joe
        client Joe send <msg>
        client Joe show 1
        '''

        def re(seq):
            return '(' + '|'.join(seq) + ')'

        grams = [
            "(\s* (?P<simple>{}) \s*) |".format(re(self.simpleCmds)),
            "(\s* (?P<client_command>{}) \s+ (?P<node_or_cli>clients?)   \s+ (?P<client_name>[a-zA-Z0-9]+) \s*) |".format(re(self.cliCmds)),
            "(\s* (?P<node_command>{}) \s+ (?P<node_or_cli>nodes?)   \s+ (?P<node_name>[a-zA-Z0-9]+)\s*) |".format(re(self.nodeCmds)),
            "(\s* (?P<client>client) \s+ (?P<client_name>[a-zA-Z0-9]+) \s+ (?P<cli_action>send) \s+ (?P<msg>\{\s*\".*\})  \s*)  |",
            "(\s* (?P<client>client) \s+ (?P<client_name>[a-zA-Z0-9]+) \s+ (?P<cli_action>show) \s+ (?P<req_id>[0-9]+)  \s*)  |",
            "(\s* (?P<load_plugins>load\s+plugins\s+from) \s+ (?P<plugin_dir>[a-zA-Z0-9-{}]+) \s*)  |".format(os.path.sep),
            "(\s* (?P<load>load) \s+ (?P<file_name>[.a-zA-z0-9{}]+) \s*) |".format(os.path.sep),
            "(\s* (?P<command>help) (\s+ (?P<helpable>[a-zA-Z0-9]+) )? (\s+ (?P<node_or_cli>{}) )?\s*) |".format(re(self.node_or_cli)),
            "(\s* (?P<command>list) \s*)".format(re(self.commands))
        ]

        self.grammar = compile("".join(grams))

        lexer = GrammarLexer(self.grammar, lexers={
            'node_command': SimpleLexer(Token.Keyword),
            'command': SimpleLexer(Token.Keyword),
            'helpable': SimpleLexer(Token.Keyword),
            'load_plugins': SimpleLexer(Token.Keyword),
            'load': SimpleLexer(Token.Keyword),
            'node_or_cli': SimpleLexer(Token.Keyword),
            'arg1': SimpleLexer(Token.Name),
            'node_name': SimpleLexer(Token.Name),
            'more_nodes': SimpleLexer(Token.Name),
            'simple': SimpleLexer(Token.Keyword),
            'client_command': SimpleLexer(Token.Keyword),
        })

        self.clientWC = WordCompleter([])

        completer = GrammarCompleter(self.grammar, {
            'node_command': WordCompleter(self.nodeCmds),
            'client_command': WordCompleter(self.cliCmds),
            'client': WordCompleter(['client']),
            'command': WordCompleter(self.commands),
            'node_or_cli': WordCompleter(self.node_or_cli),
            'node_name': WordCompleter(self.nodeNames),
            'more_nodes': WordCompleter(self.nodeNames),
            'helpable': WordCompleter(self.helpablesCommands),
            'load_plugins': WordCompleter(['load plugins from']),
            'client_name': self.clientWC,
            'cli_action': WordCompleter(self.cliActions),
            'simple': WordCompleter(self.simpleCmds)
        })

        self.style = PygmentsStyle.from_defaults({
            Token.Operator: '#33aa33 bold',
            Token.Number: '#aa3333 bold',
            Token.Name: '#ffff00 bold',
            Token.Heading: 'bold',
            Token.TrailingInput: 'bg:#662222 #ffffff',
            Token.BoldGreen: '#33aa33 bold',
            Token.BoldOrange: '#ff4f2f bold',
            Token.BoldBlue: '#095cab bold'})

        self.functionMappings = self.createFunctionMappings()

        self.voidMsg = "<none>"

        # Create an asyncio `EventLoop` object. This is a wrapper around the
        # asyncio loop that can be passed into prompt_toolkit.
        eventloop = create_asyncio_eventloop(looper.loop)

        pers_hist = FileHistory('.plenum-cli-history')

        # Create interface.
        app = create_prompt_application('plenum> ',
                                        lexer=lexer,
                                        completer=completer,
                                        style=self.style,
                                        history=pers_hist)
        self.cli = CommandLineInterface(
            application=app,
            eventloop=eventloop,
            output=CustomOutput.from_pty(sys.__stdout__, true_color=True))

        # Patch stdout in something that will always print *above* the prompt
        # when something is written to stdout.
        sys.stdout = self.cli.stdout_proxy()
        setupLogging(TRACE_LOG_LEVEL,
                     Console.Wordage.mute,
                     filename=logFileName)

        self.logger = getlogger("cli")
        self.print("\nplenum-CLI (c) 2016 Evernym, Inc.")
        self.print("Node registry loaded.")
        self.print("None of these are created or running yet.")

        self.showNodeRegistry()
        self.print("Type 'help' for more information.")
Esempio n. 30
0
import prompt_toolkit.shortcuts
from prompt_toolkit.shortcuts import create_prompt_application, create_asyncio_eventloop, prompt_async
from prompt_toolkit.styles import style_from_dict
from prompt_toolkit.token import Token
import sys

import logging
import importlib
logging.basicConfig(level='ERROR')
import concurrent
import asyncio
import unha2.client as client
from unha2.model.base import RoomType
from unha2.methods import MethodError

eventloop = create_asyncio_eventloop()
cli = CommandLineInterface(
    application=create_prompt_application('> '),
    eventloop=eventloop)
sys.stdout = cli.stdout_proxy()

STYLE_DICT = {
    Token.Title: 'bold',
    Token.Error: '#ansired',
    Token.Nick: '#ansiyellow',
    Token.Server: '#ansiblue',
    Token.Chat: '#ansigreen',
    Token.Direct: '#ansifuchsia',
    Token.Private: '#ansiblue',
    Token.Time: '#ansilightgray',
    Token.Separator: '#ansilightgray bold',
Esempio n. 31
0
File: xc.py Progetto: jbg/xc
async def xmpp_client():
    try:
        with open(os.path.join(os.getenv("HOME"), ".xc.conf"),
                  "r") as config_file:
            config = json.load(config_file)
        if "jid" not in config:
            raise Exception("No JID")
    except Exception as e:
        print(
            "Error reading configuration file.\n" + str(e) +
            "Please create ~/.xc.conf with content like:\n{\"jid\": \"[email protected]\"}"
        )
        sys.exit(1)

    async def get_secret(jid, attempt):
        if attempt > 2:
            return None
        try:
            return await prompt_async("Secret (will not be stored): ",
                                      is_password=True)
        except:
            return None

    async def tls_handshake_callback(verifier):
        print("Warning: blindly accepting TLS certificate from %s" %
              verifier.transport.get_extra_info("server_hostname"))
        return True

    pin_store = PublicKeyPinStore()
    pin_store.import_from_json(config.get("pkps", {}))
    my_jid = aioxmpp.JID.fromstr(config["jid"])
    security = aioxmpp.make_security_layer(
        get_secret,
        pin_store=pin_store,
        pin_type=PinType.PUBLIC_KEY,
        post_handshake_deferred_failure=tls_handshake_callback)
    client = aioxmpp.PresenceManagedClient(my_jid, security)
    presence = client.summon(aioxmpp.presence.Service)
    roster = client.summon(aioxmpp.roster.Service)

    class RosterItemAndCommandCompleter(Completer):
        def get_completions(self, document, complete_event):
            text = document.text
            if not text or " " in text or ":" in text:
                return
            if text[0] == "/":
                part = text[1:]
                for command in ("roster", "name", "add", "del", "help",
                                "quit"):
                    if command.startswith(part):
                        yield Completion(command + " ",
                                         start_position=-len(part),
                                         display=command)
            elif roster is not None:
                for item in roster.items.values():
                    if item.name.startswith(text):
                        yield Completion(item.name + ": ",
                                         start_position=-len(text),
                                         display=item.name)

    completer = RosterItemAndCommandCompleter()
    history = InMemoryHistory()

    next_recipient = None

    def get_prompt_tokens(_):
        return ((Token.Prompt, "%s> " % (next_recipient or "")), )

    cli_app = create_prompt_application(get_prompt_tokens=get_prompt_tokens,
                                        completer=completer,
                                        reserve_space_for_menu=0,
                                        history=history,
                                        get_title=lambda: "xc")
    cli_loop = create_asyncio_eventloop()
    cli = CommandLineInterface(application=cli_app, eventloop=cli_loop)
    above_prompt = cli.stdout_proxy()

    def name_for_jid(jid):
        try:
            return roster.items[jid].name
        except:
            return str(jid)

    def peer_available(jid, presence):
        above_prompt.write("%s is now online\n" % name_for_jid(jid.bare()))

    presence.on_available.connect(peer_available)

    def peer_unavailable(jid, presence):
        above_prompt.write("%s is now offline\n" % name_for_jid(jid.bare()))

    presence.on_unavailable.connect(peer_unavailable)

    def message_received(msg):
        content = " ".join(msg.body.values())
        if content:
            above_prompt.write("%s: %s\n" %
                               (name_for_jid(msg.from_.bare()), content))

    client.stream.register_message_callback("chat", None, message_received)

    try:
        async with client.connected() as stream:
            while True:
                try:
                    document = await cli.run_async()
                except (KeyboardInterrupt, EOFError):
                    break
                line = document.text
                if line.startswith("/"):
                    try:
                        command, *args = line[1:].split(" ")
                        if command == "roster":
                            rows = [(item.name, str(jid), item.subscription)
                                    for jid, item in roster.items.items()
                                    if jid != my_jid]
                            widths = [
                                max(len(row[i] or "") for row in rows)
                                for i in range(len(rows[0] or ""))
                            ]
                            for row in rows:
                                above_prompt.write("   ".join(
                                    (cell or "").ljust(widths[i])
                                    for i, cell in enumerate(row)) + "\n")
                        elif command == "name":
                            try:
                                jid = args[0]
                                name = args[1]
                            except IndexError:
                                above_prompt.write("usage: /name JID NAME\n")
                            else:
                                jid = aioxmpp.JID.fromstr(jid)
                                await roster.set_entry(jid, name=name)
                        elif command == "add":
                            try:
                                jid = args[0]
                            except IndexError:
                                above_prompt.write("usage: /add JID\n")
                            else:
                                jid = aioxmpp.JID.fromstr(jid)
                                await roster.set_entry(jid)
                                roster.subscribe(jid)
                                roster.approve(jid)
                        elif command == "del":
                            try:
                                jid = args[0]
                            except IndexError:
                                above_prompt.write("usage: /del JID\n")
                            else:
                                jid = aioxmpp.JID.fromstr(jid)
                                await roster.remove_entry(jid)
                        elif command == "quit":
                            break
                        elif command == "help":
                            above_prompt.write(
                                "NAME: MESSAGE    send MESSAGE to NAME\n"
                                "MESSAGE          send MESSAGE to the last correspondent\n"
                                "/roster          print the roster\n"
                                "/add JID         add JID to the roster\n"
                                "/del JID         remove JID from the roster\n"
                                "/name JID NAME   set the name of JID to NAME\n"
                                "/quit            disconnect and then quit (also ctrl-d, ctrl-c)\n"
                                "/help            this help\n")
                        else:
                            above_prompt.write("unrecognised command\n")
                    except Exception as e:
                        above_prompt.write("exception handling command: %s\n" %
                                           e)
                else:
                    try:
                        try:
                            recipient, message = line.split(": ", 1)
                        except ValueError:
                            if next_recipient is not None:
                                recipient = next_recipient
                                message = line
                            else:
                                above_prompt.write("recipient: message\n")
                                continue
                        jid_for_name = lambda r: next(
                            (jid for jid, item in roster.items.items()
                             if item.name == r), None)
                        jid = jid_for_name(recipient)
                        if jid is None:
                            if next_recipient is not None and recipient != next_recipient:
                                recipient = next_recipient
                                jid = jid_for_name(recipient)
                                message = line
                        if jid is None:
                            above_prompt.write("unknown recipient: %s\n" %
                                               recipient)
                            continue
                        msg = aioxmpp.Message(to=jid, type_="chat")
                        msg.body[None] = message
                        await stream.send_and_wait_for_sent(msg)
                        next_recipient = recipient
                    except Exception as e:
                        above_prompt.write("exception sending message: %s\n" %
                                           e)

        print("Disconnecting…")
        client.stop()
    except Exception as e:
        print("Failed to connect: %s" % e)
Esempio n. 32
0
    def prompt(self, message='', **kwargs):
        """Get input from the user and return it.

        This is a wrapper around a lot of prompt_toolkit functionality and
        can be a replacement for raw_input. (or GNU readline.) If you want
        to keep your history across several calls, create one
        `~prompt_toolkit.history.History instance and pass it every
        time. This function accepts many keyword arguments. Except for the
        following. they are a proxy to the arguments of
        create_prompt_application().

        Parameters
        ----------
        patch_stdout : file-like, optional
            Replace ``sys.stdout`` by a proxy that ensures that print
            statements from other threads won't destroy the prompt. (They
            will be printed above the prompt instead.)
        return_asyncio_coroutine : bool, optional
            When True, return a asyncio coroutine. (Python >3.3)

        Notes
        -----
        This method was forked from the mainline prompt-toolkit repo.
        Copyright (c) 2014, Jonathan Slenders, All rights reserved.
        """
        patch_stdout = kwargs.pop('patch_stdout', False)
        return_asyncio_coroutine = kwargs.pop('return_asyncio_coroutine',
                                              False)
        if return_asyncio_coroutine:
            eventloop = create_asyncio_eventloop()
        else:
            eventloop = kwargs.pop('eventloop', None) or create_eventloop()

        # Create CommandLineInterface.
        if self.cli is None:
            if self.major_minor < (0, 57):
                kwargs.pop('reserve_space_for_menu', None)
            if self.major_minor <= (0, 57):
                kwargs.pop('get_rprompt_tokens', None)
                kwargs.pop('get_continuation_tokens', None)
            # VI_Mode handling changed in prompt_toolkit v1.0
            if self.major_minor >= (1, 0):
                from prompt_toolkit.enums import EditingMode
                if builtins.__xonsh_env__.get('VI_MODE'):
                    editing_mode = EditingMode.VI
                else:
                    editing_mode = EditingMode.EMACS
                kwargs['editing_mode'] = editing_mode
                kwargs['vi_mode'] = builtins.__xonsh_env__.get('VI_MODE')
            cli = CommandLineInterface(application=create_prompt_application(
                message, **kwargs),
                                       eventloop=eventloop,
                                       output=create_output())
            self.cli = cli
        else:
            cli = self.cli

        # Replace stdout.
        patch_context = cli.patch_stdout_context(
        ) if patch_stdout else DummyContext()

        # Read input and return it.
        if return_asyncio_coroutine:
            # Create an asyncio coroutine and call it.
            exec_context = {'patch_context': patch_context, 'cli': cli}
            exec(
                textwrap.dedent('''
            import asyncio
            @asyncio.coroutine
            def prompt_coro():
                with patch_context:
                    document = yield from cli.run_async(reset_current_buffer=False)
                    if document:
                        return document.text
            '''), exec_context)
            return exec_context['prompt_coro']()
        else:
            # Note: We pass `reset_current_buffer=False`, because that way
            # it's easy to give DEFAULT_BUFFER a default value, without it
            # getting erased. We don't have to reset anyway, because this is
            # the first and only time that this CommandLineInterface will run.
            try:
                with patch_context:
                    document = cli.run(reset_current_buffer=False)

                    if document:
                        return document.text
            finally:
                eventloop.close()
Esempio n. 33
0
    def __init__(self, looper, basedirpath, nodeReg, cliNodeReg, output=None, debug=False,
                 logFileName=None):
        self.curClientPort = None
        logging.root.addHandler(CliHandler(self.out))

        self.looper = looper
        self.basedirpath = basedirpath
        self.nodeReg = nodeReg
        self.cliNodeReg = cliNodeReg

        # Used to store created clients
        self.clients = {}  # clientName -> Client
        # To store the created requests
        self.requests = {}
        # To store the nodes created
        self.nodes = {}
        self.externalClientKeys = {}  # type: Dict[str,str]

        self.cliCmds = {'status', 'new'}
        self.nodeCmds = self.cliCmds | {'keyshare'}
        self.helpablesCommands = self.cliCmds | self.nodeCmds
        self.simpleCmds = {'status', 'exit', 'quit', 'license'}
        self.commands = {'list', 'help'} | self.simpleCmds
        self.cliActions = {'send', 'show'}
        self.commands.update(self.cliCmds)
        self.commands.update(self.nodeCmds)
        self.node_or_cli = ['node',  'client']
        self.nodeNames = list(self.nodeReg.keys()) + ["all"]
        self.debug = debug
        self.plugins = {}
        '''
        examples:
        status

        new node Alpha
        new node all
        new client Joe
        client Joe send <msg>
        client Joe show 1
        '''

        psep = re.escape(os.path.sep)

        self.utilGrams = [
            "(\s* (?P<simple>{}) \s*) |".format(self.relist(self.simpleCmds)),
            "(\s* (?P<load>load) \s+ (?P<file_name>[.a-zA-z0-9{}]+) \s*) |".format(psep),
            "(\s* (?P<command>help) (\s+ (?P<helpable>[a-zA-Z0-9]+) )? (\s+ (?P<node_or_cli>{}) )?\s*) |".format(self.relist(self.node_or_cli)),
            "(\s* (?P<command>list) \s*)"
        ]

        self.nodeGrams = [
            "(\s* (?P<node_command>{}) \s+ (?P<node_or_cli>nodes?)   \s+ (?P<node_name>[a-zA-Z0-9]+)\s*) |".format(self.relist(self.nodeCmds)),
            "(\s* (?P<load_plugins>load\s+plugins\s+from) \s+ (?P<plugin_dir>[a-zA-Z0-9-:{}]+) \s*)".format(psep),
        ]

        self.clientGrams = [
            "(\s* (?P<client_command>{}) \s+ (?P<node_or_cli>clients?)   \s+ (?P<client_name>[a-zA-Z0-9]+) \s*) |".format(self.relist(self.cliCmds)),
            "(\s* (?P<client>client) \s+ (?P<client_name>[a-zA-Z0-9]+) \s+ (?P<cli_action>send) \s+ (?P<msg>\{\s*.*\})  \s*)  |",
            "(\s* (?P<client>client) \s+ (?P<client_name>[a-zA-Z0-9]+) \s+ (?P<cli_action>show) \s+ (?P<req_id>[0-9]+)  \s*)  |",
            "(\s* (?P<add_key>add\s+key) \s+ (?P<verkey>[a-fA-F0-9]+) \s+ (?P<for_client>for\s+client) \s+ (?P<identifier>[a-zA-Z0-9]+) \s*)",
        ]

        self.lexers = {
            'node_command': SimpleLexer(Token.Keyword),
            'command': SimpleLexer(Token.Keyword),
            'helpable': SimpleLexer(Token.Keyword),
            'load_plugins': SimpleLexer(Token.Keyword),
            'load': SimpleLexer(Token.Keyword),
            'node_or_cli': SimpleLexer(Token.Keyword),
            'arg1': SimpleLexer(Token.Name),
            'node_name': SimpleLexer(Token.Name),
            'more_nodes': SimpleLexer(Token.Name),
            'simple': SimpleLexer(Token.Keyword),
            'client_command': SimpleLexer(Token.Keyword),
            'add_key': SimpleLexer(Token.Keyword),
            'verkey': SimpleLexer(Token.Literal),
            'for_client': SimpleLexer(Token.Keyword),
            'identifier': SimpleLexer(Token.Name),
        }

        self.clientWC = WordCompleter([])

        self.completers = {
            'node_command': WordCompleter(self.nodeCmds),
            'client_command': WordCompleter(self.cliCmds),
            'client': WordCompleter(['client']),
            'command': WordCompleter(self.commands),
            'node_or_cli': WordCompleter(self.node_or_cli),
            'node_name': WordCompleter(self.nodeNames),
            'more_nodes': WordCompleter(self.nodeNames),
            'helpable': WordCompleter(self.helpablesCommands),
            'load_plugins': WordCompleter(['load plugins from']),
            'client_name': self.clientWC,
            'cli_action': WordCompleter(self.cliActions),
            'simple': WordCompleter(self.simpleCmds),
            'add_key': WordCompleter(['add key']),
            'for_client': WordCompleter(['for client']),
        }

        self.initializeGrammar()

        self.initializeGrammarLexer()

        self.initializeGrammarCompleter()

        self.style = PygmentsStyle.from_defaults({
            Token.Operator: '#33aa33 bold',
            Token.Number: '#aa3333 bold',
            Token.Name: '#ffff00 bold',
            Token.Heading: 'bold',
            Token.TrailingInput: 'bg:#662222 #ffffff',
            Token.BoldGreen: '#33aa33 bold',
            Token.BoldOrange: '#ff4f2f bold',
            Token.BoldBlue: '#095cab bold'})

        self.functionMappings = self.createFunctionMappings()

        self.voidMsg = "<none>"

        # Create an asyncio `EventLoop` object. This is a wrapper around the
        # asyncio loop that can be passed into prompt_toolkit.
        eventloop = create_asyncio_eventloop(looper.loop)

        pers_hist = FileHistory('.{}-cli-history'.format(self.name))

        # Create interface.
        app = create_prompt_application('{}> '.format(self.name),
                                        lexer=self.grammarLexer,
                                        completer=self.grammarCompleter,
                                        style=self.style,
                                        history=pers_hist)

        if output:
            out = output
        else:
            if is_windows():
                if is_conemu_ansi():
                    out = ConEmuOutput(sys.__stdout__)
                else:
                    out = Win32Output(sys.__stdout__)
            else:
                out = CustomOutput.from_pty(sys.__stdout__, true_color=True)

        self.cli = CommandLineInterface(
            application=app,
            eventloop=eventloop,
            output=out)

        # Patch stdout in something that will always print *above* the prompt
        # when something is written to stdout.
        sys.stdout = self.cli.stdout_proxy()
        setupLogging(TRACE_LOG_LEVEL,
                     Console.Wordage.mute,
                     filename=logFileName)

        self.logger = getlogger("cli")
        self.print("\n{}-CLI (c) 2016 Evernym, Inc.".format(self.properName))
        self.print("Node registry loaded.")
        self.print("None of these are created or running yet.")

        self.showNodeRegistry()
        self.print("Type 'help' for more information.")
Esempio n. 34
0
    def prompt(self, message='', **kwargs):
        """Get input from the user and return it.

        This is a wrapper around a lot of prompt_toolkit functionality and
        can be a replacement for raw_input. (or GNU readline.) If you want
        to keep your history across several calls, create one
        `~prompt_toolkit.history.History instance and pass it every
        time. This function accepts many keyword arguments. Except for the
        following. they are a proxy to the arguments of
        create_prompt_application().

        Parameters
        ----------
        patch_stdout : file-like, optional
            Replace ``sys.stdout`` by a proxy that ensures that print
            statements from other threads won't destroy the prompt. (They
            will be printed above the prompt instead.)
        return_asyncio_coroutine : bool, optional
            When True, return a asyncio coroutine. (Python >3.3)

        Notes
        -----
        This method was forked from the mainline prompt-toolkit repo.
        Copyright (c) 2014, Jonathan Slenders, All rights reserved.
        """
        patch_stdout = kwargs.pop('patch_stdout', False)
        return_asyncio_coroutine = kwargs.pop('return_asyncio_coroutine', False)
        if return_asyncio_coroutine:
            eventloop = create_asyncio_eventloop()
        else:
            eventloop = kwargs.pop('eventloop', None) or create_eventloop()

        # Create CommandLineInterface.
        if self.cli is None:
            if self.major_minor < (0, 57):
                kwargs.pop('reserve_space_for_menu', None)
            if self.major_minor <= (0, 57):
                kwargs.pop('get_rprompt_tokens', None)
                kwargs.pop('get_continuation_tokens', None)
            # VI_Mode handling changed in prompt_toolkit v1.0
            if self.major_minor >= (1, 0):
                from prompt_toolkit.enums import EditingMode
                if builtins.__xonsh_env__.get('VI_MODE'):
                    editing_mode = EditingMode.VI
                else:
                    editing_mode = EditingMode.EMACS
                kwargs['editing_mode'] = editing_mode
                kwargs['vi_mode'] = builtins.__xonsh_env__.get('VI_MODE')
            cli = CommandLineInterface(
                application=create_prompt_application(message, **kwargs),
                eventloop=eventloop,
                output=create_output())
            self.cli = cli
        else:
            cli = self.cli

        # Replace stdout.
        patch_context = cli.patch_stdout_context() if patch_stdout else DummyContext()

        # Read input and return it.
        if return_asyncio_coroutine:
            # Create an asyncio coroutine and call it.
            exec_context = {'patch_context': patch_context, 'cli': cli}
            exec(textwrap.dedent('''
            import asyncio
            @asyncio.coroutine
            def prompt_coro():
                with patch_context:
                    document = yield from cli.run_async(reset_current_buffer=False)
                    if document:
                        return document.text
            '''), exec_context)
            return exec_context['prompt_coro']()
        else:
            # Note: We pass `reset_current_buffer=False`, because that way
            # it's easy to give DEFAULT_BUFFER a default value, without it
            # getting erased. We don't have to reset anyway, because this is
            # the first and only time that this CommandLineInterface will run.
            try:
                with patch_context:
                    document = cli.run(reset_current_buffer=False)

                    if document:
                        return document.text
            finally:
                eventloop.close()
Esempio n. 35
0
def embed(globals=None,
          locals=None,
          configure=None,
          vi_mode=False,
          history_filename=None,
          title=None,
          startup_paths=None,
          patch_stdout=False,
          return_asyncio_coroutine=False):
    """
    Call this to embed  Python shell at the current point in your program.
    It's similar to `IPython.embed` and `bpython.embed`. ::

        from prompt_toolkit.contrib.repl import embed
        embed(globals(), locals())

    :param vi_mode: Boolean. Use Vi instead of Emacs key bindings.
    :param configure: Callable that will be called with the `PythonRepl` as a first
                      argument, to trigger configuration.
    :param title: Title to be displayed in the terminal titlebar. (None or string.)
    """
    assert configure is None or callable(configure)

    # Default globals/locals
    if globals is None:
        globals = {
            '__name__': '__main__',
            '__package__': None,
            '__doc__': None,
            '__builtins__': six.moves.builtins,
        }

    locals = locals or globals

    def get_globals():
        return globals

    def get_locals():
        return locals

    # Create eventloop.
    if return_asyncio_coroutine:
        eventloop = create_asyncio_eventloop()
    else:
        eventloop = create_eventloop()

    # Create REPL.
    repl = PythonRepl(get_globals,
                      get_locals,
                      vi_mode=vi_mode,
                      history_filename=history_filename,
                      startup_paths=startup_paths)

    if title:
        repl.terminal_title = title

    if configure:
        configure(repl)

    cli = PythonCommandLineInterface(python_input=repl, eventloop=eventloop)

    # Start repl.
    patch_context = cli.patch_stdout_context(
    ) if patch_stdout else DummyContext()

    if return_asyncio_coroutine:

        def coroutine():
            with patch_context:
                for future in cli.run_async():
                    yield future

        return coroutine()
    else:
        with patch_context:
            cli.run()
Esempio n. 36
0
        cList[data.username] = self

    def handle_request(self, data):
        print(data)
        if data.req == "contacts":
            contacts = self.db.query_contact(self.username)
            print("{0:s} [SERVER]: contacts for: {1:}".format(
                tstamp(), self.username))
            print(*tuple(contacts[i] for i in range(len(contacts))), sep="\n")

            for c in contacts:
                self.send("{}".format(c))


# ===============================================================================

if __name__ == '__main__':
    print("{0:s} [SERVER]: starting.".format(tstamp()))
    loop = asyncio.get_event_loop()
    coroutine = loop.create_server(Server, '127.0.0.1', 9999)

    server = loop.run_until_complete(coroutine)
    asyncio. async (server_console(create_asyncio_eventloop(loop)))
    for socket in server.sockets:
        print("{0:s} [SERVER]: running on {1:}".format(tstamp(),
                                                       socket.getsockname()))
    try:
        loop.run_forever()
    except KeyboardInterrupt:
        pass