Example #1
0
File: kytosd.py Project: kytos/kyco
def start_shell(controller=None):
    """Load Kytos interactive shell."""
    kytos_ascii = r"""
      _          _
     | |        | |
     | | ___   _| |_ ___  ___
     | |/ / | | | __/ _ \/ __|
     |   <| |_| | || (_) \__ \
     |_|\_\__,  |\__\___/|___/
            __/ |
           |___/
    """

    banner1 = f"""\033[95m{kytos_ascii}\033[0m
    Welcome to Kytos SDN Platform!

    We are making a huge effort to make sure that this console will work fine
    but for now it's still experimental.

    Kytos website.: https://kytos.io/
    Documentation.: https://docs.kytos.io/
    OF Address....:"""

    exit_msg = "Stopping Kytos daemon... Bye, see you!"

    if controller:
        address = controller.server.server_address[0]
        port = controller.server.server_address[1]
        banner1 += f" tcp://{address}:{port}\n"

        api_port = controller.api_server.port
        banner1 += f"    WEB UI........: http://{address}:{api_port}/\n"
        banner1 += f"    Kytos Version.: {__version__}"

    banner1 += "\n"

    cfg = Config()
    cfg.TerminalInteractiveShell.autocall = 2
    cfg.TerminalInteractiveShell.show_rewritten_input = False
    cfg.TerminalInteractiveShell.confirm_exit = False

    # Avoiding sqlite3.ProgrammingError when trying to save command history
    # on Kytos shutdown
    cfg.HistoryAccessor.enabled = False

    ipshell = InteractiveShellEmbed(config=cfg,
                                    banner1=banner1,
                                    exit_msg=exit_msg)
    ipshell.prompts = KytosPrompt(ipshell)

    ipshell()
Example #2
0
def start_shell(controller=None):
    """Load Kytos interactive shell."""
    kytos_ascii = r"""
      _          _
     | |        | |
     | | ___   _| |_ ___  ___
     | |/ / | | | __/ _ \/ __|
     |   <| |_| | || (_) \__ \
     |_|\_\__,  |\__\___/|___/
            __/ |
           |___/
    """

    banner1 = f"""\033[95m{kytos_ascii}\033[0m
    Welcome to Kytos SDN Platform!

    We are making a huge effort to make sure that this console will work fine
    but for now it's still experimental.

    Kytos website.: https://kytos.io/
    Documentation.: https://docs.kytos.io/
    OF Address....:"""

    exit_msg = "Stopping Kytos daemon... Bye, see you!"

    if controller:
        address = controller.server.server_address[0]
        port = controller.server.server_address[1]
        banner1 += f" tcp://{address}:{port}\n"

        api_port = controller.api_server.port
        banner1 += f"    WEB UI........: http://{address}:{api_port}/\n"
        banner1 += f"    Kytos Version.: {__version__}"

    banner1 += "\n"

    cfg = Config()
    cfg.TerminalInteractiveShell.autocall = 2
    cfg.TerminalInteractiveShell.show_rewritten_input = False
    cfg.TerminalInteractiveShell.confirm_exit = False

    # Avoiding sqlite3.ProgrammingError when trying to save command history
    # on Kytos shutdown
    cfg.HistoryAccessor.enabled = False

    ipshell = InteractiveShellEmbed(config=cfg,
                                    banner1=banner1,
                                    exit_msg=exit_msg)
    ipshell.prompts = KytosPrompt(ipshell)

    ipshell()
Example #3
0
def start_shell(controller):
    """Load Kytos interactive shell."""
    # pylint: disable=anomalous-backslash-in-string
    banner1 = """\033[95m
      _          _
     | |        | |
     | | ___   _| |_ ___  ___
     | |/ / | | | __/ _ \/ __|
     |   <| |_| | || (_) \__ \\
     |_|\_\\\\__, |\__\___/|___/
            __/ |
           |___/
    \033[0m
    Welcome to Kytos SDN Platform!

    We are doing a huge effort to make sure that this console will work fine
    but for now it's still experimental.

    Kytos website.: https://kytos.io/
    Documentation.: https://docs.kytos.io/
    OF Address....:"""

    exit_msg = "Stopping Kytos daemon... Bye, see you!"

    address = controller.server.server_address[0]
    port = controller.server.server_address[1]
    banner1 += " tcp://{}:{}\n".format(address, port)

    api_port = controller.api_server.port
    banner1 += "    WEB UI........: http://{}:{}/".format(address, api_port)

    cfg = Config()
    cfg.TerminalInteractiveShell.autocall = 2
    cfg.TerminalInteractiveShell.show_rewritten_input = False

    ipshell = InteractiveShellEmbed(config=cfg,
                                    banner1=banner1,
                                    exit_msg=exit_msg)
    ipshell.prompts = KytosPrompt(ipshell)

    ipshell()
Example #4
0
def interface_shell_embed(interface):
    """
    Returns an IPython shell which uses a Sage interface on the
    backend to perform the evaluations.  It uses
    :class:`InterfaceShellTransformer` to transform the input into the
    appropriate ``interface.eval(...)`` input.

    INPUT:

    - ``interface`` -- A Sage ``PExpect`` interface instance.

    EXAMPLES::

        sage: from sage.repl.interpreter import interface_shell_embed
        sage: shell = interface_shell_embed(gap)
        sage: shell.run_cell('List( [1..10], IsPrime )')
        [ false, true, true, false, true, false, true, false, false, false ]
        <repr(<IPython.core.interactiveshell.ExecutionResult at 0x...>) failed: 
        AttributeError: type object 'ExecutionResult' has no attribute '__qualname__'>

    Note that the repr error is https://github.com/ipython/ipython/issues/9756
    """
    cfg = sage_ipython_config.copy()
    ipshell = InteractiveShellEmbed(config=cfg,
                                    banner1='\n  --> Switching to %s <--\n\n'%interface,
                                    exit_msg='\n  --> Exiting back to Sage <--\n')
    ipshell.interface = interface
    ipshell.prompts = InterfacePrompts(interface.name())

    while ipshell.prefilter_manager.transformers:
        ipshell.prefilter_manager.transformers.pop()
    while ipshell.prefilter_manager.checkers:
        ipshell.prefilter_manager.checkers.pop()
    ipshell.ex('import sage.misc.all')

    InterfaceShellTransformer(shell=ipshell,
                              prefilter_manager=ipshell.prefilter_manager,
                              config=cfg)
    return ipshell
Example #5
0
def interface_shell_embed(interface):
    """
    Returns an IPython shell which uses a Sage interface on the
    backend to perform the evaluations.  It uses
    :class:`InterfaceShellTransformer` to transform the input into the
    appropriate ``interface.eval(...)`` input.

    INPUT:

    - ``interface`` -- A Sage ``PExpect`` interface instance.

    EXAMPLES::

        sage: from sage.repl.interpreter import interface_shell_embed
        sage: shell = interface_shell_embed(gap)
        sage: shell.run_cell('List( [1..10], IsPrime )')
        [ false, true, true, false, true, false, true, false, false, false ]
        <ExecutionResult object at ..., execution_count=None error_before_exec=None error_in_exec=None result=[ false, true, true, false, true, false, true, false, false, false ]>
    """
    cfg = sage_ipython_config.copy()
    ipshell = InteractiveShellEmbed(
        config=cfg,
        banner1='\n  --> Switching to %s <--\n\n' % interface,
        exit_msg='\n  --> Exiting back to Sage <--\n')
    ipshell.interface = interface
    ipshell.prompts = InterfacePrompts(interface.name())

    while ipshell.prefilter_manager.transformers:
        ipshell.prefilter_manager.transformers.pop()
    while ipshell.prefilter_manager.checkers:
        ipshell.prefilter_manager.checkers.pop()
    ipshell.ex('import sage.misc.all')

    InterfaceShellTransformer(shell=ipshell,
                              prefilter_manager=ipshell.prefilter_manager,
                              config=cfg)
    return ipshell
Example #6
0
def interface_shell_embed(interface):
    """
    Returns an IPython shell which uses a Sage interface on the
    backend to perform the evaluations.  It uses
    :class:`InterfaceShellTransformer` to transform the input into the
    appropriate ``interface.eval(...)`` input.

    INPUT:

    - ``interface`` -- A Sage ``PExpect`` interface instance.

    EXAMPLES::

        sage: from sage.repl.interpreter import interface_shell_embed
        sage: shell = interface_shell_embed(gap)
        sage: shell.run_cell('List( [1..10], IsPrime )')
        [ false, true, true, false, true, false, true, false, false, false ]
        <ExecutionResult object at ..., execution_count=None error_before_exec=None error_in_exec=None result=[ false, true, true, false, true, false, true, false, false, false ]>
    """
    cfg = sage_ipython_config.copy()
    ipshell = InteractiveShellEmbed(config=cfg,
                                    banner1='\n  --> Switching to %s <--\n\n'%interface,
                                    exit_msg='\n  --> Exiting back to Sage <--\n')
    ipshell.interface = interface
    ipshell.prompts = InterfacePrompts(interface.name())

    while ipshell.prefilter_manager.transformers:
        ipshell.prefilter_manager.transformers.pop()
    while ipshell.prefilter_manager.checkers:
        ipshell.prefilter_manager.checkers.pop()
    ipshell.ex('import sage.misc.all')

    InterfaceShellTransformer(shell=ipshell,
                              prefilter_manager=ipshell.prefilter_manager,
                              config=cfg)
    return ipshell
Example #7
0
                        '--port',
                        required=True,
                        help="GNURadio port",
                        default=52001,
                        type=int)

    args = parser.parse_args()
    imp.load_source('config', args.config)

    class MyPrompt(Prompts):
        def in_prompt_tokens(self, cli=None):
            return [(Token.Prompt, 'COMM'), (Token.Prompt, '> ')]

    cfg = Config()
    frame_decoder = FallbackResponseDecorator(
        response_frames.FrameDecoder(response_frames.frame_factories))

    def receive():
        rcv = Receiver(args.target, args.port)
        rcv.connect()
        data = rcv.decode_kiss(rcv.receive())
        rcv.disconnect()
        return frame_decoder.decode(data)

    shell = InteractiveShellEmbed(config=cfg,
                                  user_ns={'receive': receive},
                                  banner2='COMM Terminal')
    shell.prompts = MyPrompt(shell)
    shell.run_code('from telecommand import *')
    shell()
Example #8
0
def interact(argv=sys.argv):  # pragma: no cover
    conf = Conf().load()

    banner = "\033[1mSnimpy\033[0m ({0}) -- {1}.\n".format(
        snimpy.__version__, snimpy.__doc__)
    banner += "  load        -> load an additional MIB\n"
    banner += "  M           -> manager object"

    local = {
        "conf": conf,
        "M": manager.Manager,
        "load": manager.load,
        "timedelta": timedelta,
        "snmp": manager.snmp
    }

    if len(argv) <= 1:
        manager.Manager._complete = True

    for ms in conf.mibs:
        manager.load(ms)

    globals().update(local)

    if len(argv) > 1:
        argv = argv[1:]
        exec(compile(open(argv[0]).read(), argv[0], 'exec')) in local
        return

    try:
        try:
            try:
                # ipython >= 1.0
                from IPython.terminal.embed import \
                    InteractiveShellEmbed
            except ImportError:
                # ipython >= 0.11
                from IPython.frontend.terminal.embed import \
                    InteractiveShellEmbed
            import IPython
            if IPython.version_info < (4, ):
                from IPython.config.loader import Config
            else:
                from traitlets.config.loader import Config
            cfg = Config()
            try:
                # >= 5
                from IPython.terminal.prompts import Prompts, Token

                class SnimpyPrompt(Prompts):
                    def in_prompt_tokens(self, cli=None):
                        return [
                            (Token.Prompt, "Snimpy["),
                            (Token.PromptNum, str(self.shell.execution_count)),
                            (Token.Prompt, ']> '),
                        ]

                    def out_prompt_tokens(self):
                        return [
                            (Token.OutPrompt, "Snimpy["),
                            (Token.OutPromptNum,
                             str(self.shell.execution_count)),
                            (Token.OutPrompt, ']: '),
                        ]
            except ImportError:
                SnimpyPrompt = None
                try:
                    # >= 0.12
                    cfg.PromptManager.in_template = "Snimpy [\\#]> "
                    cfg.PromptManager.out_template = "Snimpy [\\#]: "
                except ImportError:
                    # 0.11
                    cfg.InteractiveShellEmbed.prompt_in1 = "Snimpy [\\#]> "
                    cfg.InteractiveShellEmbed.prompt_out = "Snimpy [\\#]: "
            if conf.ipythonprofile:
                cfg.InteractiveShellEmbed.profile = conf.ipythonprofile
            shell = InteractiveShellEmbed(config=cfg,
                                          banner1=banner,
                                          user_ns=local)
            # Not interested by traceback in this module
            shell.InteractiveTB.tb_offset += 1
            if SnimpyPrompt is not None:
                shell.prompts = SnimpyPrompt(shell)
        except ImportError:
            # ipython < 0.11
            from IPython.Shell import IPShellEmbed
            argv = [
                "-prompt_in1", "Snimpy [\\#]> ", "-prompt_out",
                "Snimpy [\\#]: "
            ]
            if conf.ipythonprofile:
                argv += ["-profile", conf.ipythonprofile]
            shell = IPShellEmbed(argv=argv, banner=banner, user_ns=local)
            # Not interested by traceback in this module
            shell.IP.InteractiveTB.tb_offset += 1
    except ImportError:
        shell = None

    if shell and conf.ipython:
        shell()
    else:
        try:
            import rlcompleter
            import readline
        except ImportError:
            readline = None
        if readline:
            if conf.histfile:
                try:
                    readline.read_history_file(
                        os.path.expanduser(conf.histfile))
                except IOError:
                    pass
                atexit.register(lambda: readline.write_history_file(
                    os.path.expanduser(conf.histfile)))

            readline.set_completer(rlcompleter.Completer(local).complete)
            readline.parse_and_bind("tab: menu-complete")
        sys.ps1 = conf.prompt
        code.interact(banner=banner, local=local)
Example #9
0
def interact(argv=sys.argv):  # pragma: no cover
    conf = Conf().load()

    banner = "\033[1mSnimpy\033[0m ({0}) -- {1}.\n".format(
        snimpy.__version__, snimpy.__doc__)
    banner += "  load        -> load an additional MIB\n"
    banner += "  M           -> manager object"

    local = {"conf": conf,
             "M": manager.Manager,
             "load": manager.load,
             "timedelta": timedelta,
             "snmp": manager.snmp
             }

    if len(argv) <= 1:
        manager.Manager._complete = True

    for ms in conf.mibs:
        manager.load(ms)

    globals().update(local)

    if len(argv) > 1:
        argv = argv[1:]
        exec(compile(open(argv[0]).read(), argv[0], 'exec')) in local
        return

    try:
        try:
            try:
                # ipython >= 1.0
                from IPython.terminal.embed import \
                    InteractiveShellEmbed
            except ImportError:
                # ipython >= 0.11
                from IPython.frontend.terminal.embed import \
                    InteractiveShellEmbed
            import IPython
            if IPython.version_info < (4,):
                from IPython.config.loader import Config
            else:
                from traitlets.config.loader import Config
            cfg = Config()
            try:
                # >= 5
                from IPython.terminal.prompts import Prompts, Token

                class SnimpyPrompt(Prompts):
                    def in_prompt_tokens(self, cli=None):
                        return [
                            (Token.Prompt, "Snimpy["),
                            (Token.PromptNum, str(self.shell.execution_count)),
                            (Token.Prompt, ']> '),
                        ]

                    def out_prompt_tokens(self):
                        return [
                            (Token.OutPrompt, "Snimpy["),
                            (Token.OutPromptNum,
                             str(self.shell.execution_count)),
                            (Token.OutPrompt, ']: '),
                        ]
            except ImportError:
                SnimpyPrompt = None
                try:
                    # >= 0.12
                    cfg.PromptManager.in_template = "Snimpy [\\#]> "
                    cfg.PromptManager.out_template = "Snimpy [\\#]: "
                except ImportError:
                    # 0.11
                    cfg.InteractiveShellEmbed.prompt_in1 = "Snimpy [\\#]> "
                    cfg.InteractiveShellEmbed.prompt_out = "Snimpy [\\#]: "
            if conf.ipythonprofile:
                cfg.InteractiveShellEmbed.profile = conf.ipythonprofile
            shell = InteractiveShellEmbed(
                config=cfg,
                banner1=banner,
                user_ns=local)
            # Not interested by traceback in this module
            shell.InteractiveTB.tb_offset += 1
            if SnimpyPrompt is not None:
                shell.prompts = SnimpyPrompt(shell)
        except ImportError:
            # ipython < 0.11
            from IPython.Shell import IPShellEmbed
            argv = ["-prompt_in1", "Snimpy [\\#]> ",
                    "-prompt_out", "Snimpy [\\#]: "]
            if conf.ipythonprofile:
                argv += ["-profile", conf.ipythonprofile]
            shell = IPShellEmbed(argv=argv,
                                 banner=banner, user_ns=local)
            # Not interested by traceback in this module
            shell.IP.InteractiveTB.tb_offset += 1
    except ImportError:
        shell = None

    if shell and conf.ipython:
        shell()
    else:
        try:
            import rlcompleter
            import readline
        except ImportError:
            readline = None
        if readline:
            if conf.histfile:
                try:
                    readline.read_history_file(
                        os.path.expanduser(conf.histfile))
                except IOError:
                    pass
                atexit.register(lambda: readline.write_history_file(
                    os.path.expanduser(conf.histfile)))

            readline.set_completer(rlcompleter.Completer(local).complete)
            readline.parse_and_bind("tab: menu-complete")
        sys.ps1 = conf.prompt
        code.interact(banner=banner, local=local)
Example #10
0
def main():
    my_parser = argparse.ArgumentParser()
    my_parser.add_argument("-q",
                           dest="quiet",
                           default=False,
                           action="store_true",
                           help="be quiet [%(default)s]")
    my_parser.add_argument("--logger",
                           type=str,
                           default="stdout",
                           choices=["stdout", "logserver"],
                           help="choose logging facility [%(default)s]")
    my_parser.add_argument(
        "--logall",
        default=False,
        action="store_true",
        help="log all (no just warning / error), [%(default)s]")
    my_parser.add_argument("args",
                           nargs=argparse.REMAINDER,
                           help="commands to execute")
    opts = my_parser.parse_args()
    if opts.args:
        opts.quiet = True
    if not opts.quiet:
        print("Starting ICSW shell ... ", end="", flush=True)

    os.environ.setdefault("DJANGO_SETTINGS_MODULE", "initat.cluster.settings")

    try:
        import django
        if not opts.quiet:
            print("django.setup() ... ", end="", flush=True)
        django.setup()
    except:
        django = None
    else:
        from initat.cluster.backbone import db_tools
        try:
            if not db_tools.is_reachable():
                django = None
        except:
            # when installing a newer icsw-client package on a machine with an old icsw-server package
            django = None

    from initat.icsw.magics import icsw_magics

    # First import the embeddable shell class
    from IPython.terminal.prompts import Prompts, Token
    from IPython.terminal.embed import InteractiveShellEmbed

    # Now create an instance of the embeddable shell. The first argument is a
    # string with options exactly as you would type them if you were starting
    # IPython at the system command line. Any parameters you want to define for
    # configuration can thus be specified here.
    ipshell = InteractiveShellEmbed(header="X", user_ns={"django": django})

    class ICSWPrompt(Prompts):
        def in_prompt_tokens(self, cli=None):
            return [
                (Token, "[CORVUS]"),
                (Token.Prompt, ">"),
            ]

    ipshell.prompts = ICSWPrompt(ipshell)

    ipshell.mouse_support = True
    ipshell.confirm_exit = False
    ipshell.autocall = 2
    # no banner
    ipshell.banner1 = ""
    ipshell.set_hook('complete_command',
                     icsw_magics.apt_completers,
                     str_key='icsw')

    if False:

        class st2(object):
            def __dir__(self):
                return ["bla", "blo"]

            def abc(self, var):
                print("*", var)

            def _ipython_key_completions_(self):
                return ["x", "y"]

            def bla(self):
                return "bla"

            def __call__(self, *args):
                return "C", args

        xicsw = st2()

        def stest(sthg):
            print("stest:", sthg)

    ipshell.register_magics(
        icsw_magics.ICSWMagics(ipshell, True if django else False))

    if opts.args:
        if "--" in opts.args:
            opts.args.remove("--")
        _args = ["icsw"]
        if opts.logall:
            _args.append("--logall")
        _args.append("--logger")
        _args.append(opts.logger)
        r = ipshell.run_cell(" ".join(_args + opts.args), silent=True)
        sys.exit(r.result)
    else:
        if not opts.quiet:
            print("done")
        from initat.cluster.backbone.models import device, device_group
        ipshell(header="Starting icsw", )