def _get_tcp_km(self):
     c = Config()
     km = MultiKernelManager(config=c)
     return km
Exemplo n.º 2
0
 def test_fromdict(self):
     c1 = Config({'Foo' : {'bar' : 1}})
     self.assertEqual(c1.Foo.__class__, Config)
     self.assertEqual(c1.Foo.bar, 1)
Exemplo n.º 3
0
 def test_pickle_config(self):
     cfg = Config()
     cfg.Foo.bar = 1
     pcfg = pickle.dumps(cfg)
     cfg2 = pickle.loads(pcfg)
     self.assertEqual(cfg2, cfg)
Exemplo n.º 4
0
 def test_getitem_section(self):
     cfg = Config()
     self.assertNotIn('Foo', cfg)
     Foo = cfg['Foo']
     assert isinstance(Foo, Config)
     self.assertIn('Foo', cfg)
Exemplo n.º 5
0
 def test_setget(self):
     c = Config()
     c.a = 10
     self.assertEqual(c.a, 10)
     self.assertEqual('b' in c, False)
    """ Save config as JSON file
    :param json_file: Filename of JSON file
    :param newconfig: New traitlets based configuration
    """
    s = json.dumps(newconfig, indent=2, separators=(',', ': '), sort_keys=True)
    json_config = os.path.join(jupyter_config_dir(), json_file)
    make_backup(json_config)
    with open(json_config, 'w') as f:
        f.write(s)

# Update nbconvert JSON configuration
json_file = 'jupyter_nbconvert_config.json'
config = load_json_config(json_file)

# Set template path, pre- and postprocessors of notebook extensions
newconfig = Config()
newconfig.Exporter.template_path = ['.', os.path.join(data_dir, 'templates')]
newconfig.Exporter.preprocessors = ["pre_codefolding.CodeFoldingPreprocessor", "pre_pymarkdown.PyMarkdownPreprocessor"]
newconfig.NbConvertApp.postprocessor_class = 'post_embedhtml.EmbedPostProcessor'
config.merge(newconfig)
config.version = 1
save_json_config(json_file, config)

# Update nbconvert PY configuration
py_config = os.path.join(jupyter_config_dir(), 'jupyter_nbconvert_config.py')
update_config(py_config)

# Update notebook JSON configuration
json_file = 'jupyter_notebook_config.json'
config = load_json_config(json_file)
Exemplo n.º 7
0
def test_from_name_config():
    """ make sure one can construct a Component subclass by name + config"""
    config = Config({"ExampleComponent": {"param": 229.0}})
    subclass = ExampleComponent.from_name("ExampleSubclass1", config=config)
    assert subclass.param == 229.0
Exemplo n.º 8
0
 def test_insert(self):
     c = Config()
     c.Containers.lis.insert(0, 'a')
     c.Containers.lis.insert(1, 'b')
     obj = Containers(config=c)
     self.assertEqual(obj.lis, ['a', 'b', -1])
Exemplo n.º 9
0
 def test_prepend(self):
     c = Config()
     c.Containers.lis.prepend([1, 2])
     c.Containers.lis.prepend([2, 3])
     obj = Containers(config=c)
     self.assertEqual(obj.lis, [2, 3, 1, 2, -1])
Exemplo n.º 10
0
 def build_extra_config(self):
     return Config()
Exemplo n.º 11
0
 def test_extend(self):
     c = Config()
     c.Containers.lis.extend(list(range(5)))
     obj = Containers(config=c)
     self.assertEqual(obj.lis, list(range(-1, 5)))
Exemplo n.º 12
0
def test_from_config_invalid_type():
    dataset = get_dataset_path("gamma_test_large.simtel.gz")
    EventSource.input_url.default_value = dataset
    config = Config({'EventSource': {'input_url': 124}})
    with pytest.raises(TraitError):
        EventSource.from_config(config=config, parent=None)
Exemplo n.º 13
0
def test_from_config():
    dataset = get_dataset_path("gamma_test_large.simtel.gz")
    config = Config({'EventSource': {'input_url': dataset}})
    reader = EventSource.from_config(config=config, parent=None)
    assert isinstance(reader, SimTelEventSource)
    assert str(reader.input_url) == dataset
 def _get_ipc_km(self):
     c = Config()
     c.KernelManager.transport = 'ipc'
     c.KernelManager.ip = 'test'
     km = MultiKernelManager(config=c)
     return km
Exemplo n.º 15
0
def kernel_config():
    """Create a config object with IPython kernel options."""
    import ipykernel
    from IPython.core.application import get_ipython_dir
    from traitlets.config.loader import Config, load_pyconfig_files

    # ---- IPython config ----
    try:
        profile_path = osp.join(get_ipython_dir(), 'profile_default')
        cfg = load_pyconfig_files(
            ['ipython_config.py', 'ipython_kernel_config.py'], profile_path)
    except:
        cfg = Config()

    # ---- Spyder config ----
    spy_cfg = Config()

    # Enable/disable certain features for testing
    testing = os.environ.get('SPY_TESTING') == 'True'
    if testing:
        # Don't load nor save history in our IPython consoles.
        spy_cfg.HistoryAccessor.enabled = False

    # Until we implement Issue 1052
    spy_cfg.InteractiveShell.xmode = 'Plain'

    # Jedi completer. It's only available in Python 3
    jedi_o = os.environ.get('SPY_JEDI_O') == 'True'
    if not PY2:
        spy_cfg.IPCompleter.use_jedi = jedi_o

    # Clear terminal arguments input.
    # This needs to be done before adding the exec_lines that come from
    # Spyder, to avoid deleting the sys module if users want to import
    # it through them.
    # See spyder-ide/spyder#15788
    clear_argv = "import sys;sys.argv = [''];del sys"
    spy_cfg.IPKernelApp.exec_lines = [clear_argv]

    # Run lines of code at startup
    run_lines_o = os.environ.get('SPY_RUN_LINES_O')
    if run_lines_o is not None:
        spy_cfg.IPKernelApp.exec_lines += ([
            x.strip() for x in run_lines_o.split(';')
        ])

    # Load %autoreload magic
    spy_cfg.IPKernelApp.exec_lines.append(
        "get_ipython().kernel._load_autoreload_magic()")

    # Load wurlitzer extension
    spy_cfg.IPKernelApp.exec_lines.append(
        "get_ipython().kernel._load_wurlitzer()")

    # Default inline backend configuration
    # This is useful to have when people doesn't
    # use our config system to configure the
    # inline backend but want to use
    # '%matplotlib inline' at runtime
    if LooseVersion(ipykernel.__version__) < LooseVersion('4.5'):
        dpi_option = 'savefig.dpi'
    else:
        dpi_option = 'figure.dpi'

    spy_cfg.InlineBackend.rc = {
        'figure.figsize': (6.0, 4.0),
        dpi_option: 72,
        'font.size': 10,
        'figure.subplot.bottom': .125,
        'figure.facecolor': 'white',
        'figure.edgecolor': 'white'
    }

    # Pylab configuration
    mpl_backend = None
    if is_module_installed('matplotlib'):
        # Set Matplotlib backend with Spyder options
        pylab_o = os.environ.get('SPY_PYLAB_O')
        backend_o = os.environ.get('SPY_BACKEND_O')
        if pylab_o == 'True' and backend_o is not None:
            mpl_backend = MPL_BACKENDS_FROM_SPYDER[backend_o]
            # Inline backend configuration
            if mpl_backend == 'inline':
                # Figure format
                format_o = os.environ.get('SPY_FORMAT_O')
                formats = INLINE_FIGURE_FORMATS
                if format_o is not None:
                    spy_cfg.InlineBackend.figure_format = formats[format_o]

                # Resolution
                resolution_o = os.environ.get('SPY_RESOLUTION_O')
                if resolution_o is not None:
                    spy_cfg.InlineBackend.rc[dpi_option] = float(resolution_o)

                # Figure size
                width_o = float(os.environ.get('SPY_WIDTH_O'))
                height_o = float(os.environ.get('SPY_HEIGHT_O'))
                if width_o is not None and height_o is not None:
                    spy_cfg.InlineBackend.rc['figure.figsize'] = (width_o,
                                                                  height_o)

                # Print figure kwargs
                bbox_inches_o = os.environ.get('SPY_BBOX_INCHES_O')
                bbox_inches = 'tight' if bbox_inches_o == 'True' else None
                spy_cfg.InlineBackend.print_figure_kwargs.update(
                    {'bbox_inches': bbox_inches})
        else:
            # Set Matplotlib backend to inline for external kernels.
            # Fixes issue 108
            mpl_backend = 'inline'

        # Automatically load Pylab and Numpy, or only set Matplotlib
        # backend
        autoload_pylab_o = os.environ.get('SPY_AUTOLOAD_PYLAB_O') == 'True'
        command = "get_ipython().kernel._set_mpl_backend('{0}', {1})"
        spy_cfg.IPKernelApp.exec_lines.append(
            command.format(mpl_backend, autoload_pylab_o))

    # Enable Cython magic
    run_cython = os.environ.get('SPY_RUN_CYTHON') == 'True'
    if run_cython and is_module_installed('Cython'):
        spy_cfg.IPKernelApp.exec_lines.append('%reload_ext Cython')

    # Run a file at startup
    use_file_o = os.environ.get('SPY_USE_FILE_O')
    run_file_o = os.environ.get('SPY_RUN_FILE_O')
    if use_file_o == 'True' and run_file_o is not None:
        if osp.exists(run_file_o):
            spy_cfg.IPKernelApp.file_to_run = run_file_o

    # Autocall
    autocall_o = os.environ.get('SPY_AUTOCALL_O')
    if autocall_o is not None:
        spy_cfg.ZMQInteractiveShell.autocall = int(autocall_o)

    # To handle the banner by ourselves in IPython 3+
    spy_cfg.ZMQInteractiveShell.banner1 = ''

    # Greedy completer
    greedy_o = os.environ.get('SPY_GREEDY_O') == 'True'
    spy_cfg.IPCompleter.greedy = greedy_o

    # Sympy loading
    sympy_o = os.environ.get('SPY_SYMPY_O') == 'True'
    if sympy_o and is_module_installed('sympy'):
        lines = sympy_config(mpl_backend)
        spy_cfg.IPKernelApp.exec_lines.append(lines)

    # Merge IPython and Spyder configs. Spyder prefs will have prevalence
    # over IPython ones
    cfg._merge(spy_cfg)
    return cfg
Exemplo n.º 16
0
 def test_extend_append(self):
     c = Config()
     c.Containers.lis.extend([2, 3])
     c.Containers.lis.append([1, 2])
     obj = Containers(config=c)
     self.assertEqual(obj.lis, [-1, 2, 3, [1, 2]])
Exemplo n.º 17
0
    "Use a rich interactive prompt with prompt_toolkit",
)

addflag('banner', 'TerminalIPythonApp.display_banner',
        "Display a banner upon starting IPython.",
        "Don't display a banner upon starting IPython.")
addflag(
    'confirm-exit', 'TerminalInteractiveShell.confirm_exit',
    """Set to confirm when you try to exit IPython with an EOF (Control-D
    in Unix, Control-Z/Enter in Windows). By typing 'exit' or 'quit',
    you can force a direct exit without any confirmation.""",
    "Don't prompt the user when exiting.")
addflag('term-title', 'TerminalInteractiveShell.term_title',
        "Enable auto setting the terminal title.",
        "Disable auto setting the terminal title.")
classic_config = Config()
classic_config.InteractiveShell.cache_size = 0
classic_config.PlainTextFormatter.pprint = False
classic_config.TerminalInteractiveShell.prompts_class = 'IPython.terminal.prompts.ClassicPrompts'
classic_config.InteractiveShell.separate_in = ''
classic_config.InteractiveShell.separate_out = ''
classic_config.InteractiveShell.separate_out2 = ''
classic_config.InteractiveShell.colors = 'NoColor'
classic_config.InteractiveShell.xmode = 'Plain'

frontend_flags['classic'] = (
    classic_config,
    "Gives IPython a similar feel to the classic Python prompt.")
# # log doesn't make so much sense this way anymore
# paa('--log','-l',
#     action='store_true', dest='InteractiveShell.logstart',
Exemplo n.º 18
0
 def test_insert_extend(self):
     c = Config()
     c.Containers.lis.insert(0, 1)
     c.Containers.lis.extend([2, 3])
     obj = Containers(config=c)
     self.assertEqual(obj.lis, [1, -1, 2, 3])
Exemplo n.º 19
0
def interact(mydict=None, argv=None, mybanner=None, loglevel=20):
    global SESSION
    global GLOBKEYS

    console_handler = logging.StreamHandler()
    console_handler.setFormatter(
        logging.Formatter("%(levelname)s: %(message)s"))  # noqa: E501
    log_scapy.addHandler(console_handler)

    from scapy.config import conf
    conf.color_theme = DefaultTheme()
    conf.interactive = True
    if loglevel is not None:
        conf.logLevel = loglevel

    STARTUP_FILE = DEFAULT_STARTUP_FILE
    PRESTART_FILE = DEFAULT_PRESTART_FILE

    session_name = None

    if argv is None:
        argv = sys.argv

    try:
        opts = getopt.getopt(argv[1:], "hs:Cc:Pp:d")
        for opt, parm in opts[0]:
            if opt == "-h":
                _usage()
            elif opt == "-s":
                session_name = parm
            elif opt == "-c":
                STARTUP_FILE = parm
            elif opt == "-C":
                STARTUP_FILE = None
            elif opt == "-p":
                PRESTART_FILE = parm
            elif opt == "-P":
                PRESTART_FILE = None
            elif opt == "-d":
                conf.logLevel = max(1, conf.logLevel - 10)

        if len(opts[1]) > 0:
            raise getopt.GetoptError("Too many parameters : [%s]" %
                                     " ".join(opts[1]))  # noqa: E501

    except getopt.GetoptError as msg:
        log_loading.error(msg)
        sys.exit(1)

    # Reset sys.argv, otherwise IPython thinks it is for him
    sys.argv = sys.argv[:1]

    init_session(session_name, mydict)

    if STARTUP_FILE:
        _read_config_file(STARTUP_FILE, interactive=True)
    if PRESTART_FILE:
        _read_config_file(PRESTART_FILE, interactive=True)

    if not conf.interactive_shell or conf.interactive_shell.lower() in [
            "ipython", "auto"
    ]:
        try:
            import IPython
            from IPython import start_ipython
        except ImportError:
            log_loading.warning(
                "IPython not available. Using standard Python shell "
                "instead.\nAutoCompletion, History are disabled.")
            if WINDOWS:
                log_loading.warning(
                    "IPython not available. On Windows, colors are disabled"
                )  # noqa: E501
                conf.color_theme = BlackAndWhite()
            IPYTHON = False
        else:
            IPYTHON = True
    else:
        IPYTHON = False

    if conf.fancy_prompt:

        the_logo = [
            "                                      ",
            "                     aSPY//YASa       ",
            "             apyyyyCY//////////YCa    ",
            "            sY//////YSpcs  scpCY//Pp  ",
            " ayp ayyyyyyySCP//Pp           syY//C ",
            " AYAsAYYYYYYYY///Ps              cY//S",
            "         pCCCCY//p          cSSps y//Y",
            "         SPPPP///a          pP///AC//Y",
            "              A//A            cyP////C",
            "              p///Ac            sC///a",
            "              P////YCpc           A//A",
            "       scccccp///pSP///p          p//Y",
            "      sY/////////y  caa           S//P",
            "       cayCyayP//Ya              pY/Ya",
            "        sY/PsY////YCc          aC//Yp ",
            "         sc  sccaCY//PCypaapyCP//YSs  ",
            "                  spCPY//////YPSps    ",
            "                       ccaacs         ",
            "                                      ",
        ]

        the_banner = [
            "",
            "",
            "   |",
            "   | Welcome to Scapy",
            "   | Version %s" % conf.version,
            "   |",
            "   | https://github.com/secdev/scapy",
            "   |",
            "   | Have fun!",
            "   |",
        ]

        quote, author = choice(QUOTES)
        the_banner.extend(_prepare_quote(quote, author, max_len=39))
        the_banner.append("   |")
        the_banner = "\n".join(
            logo + banner
            for logo, banner in six.moves.zip_longest((
                conf.color_theme.logo(line)
                for line in the_logo), (conf.color_theme.success(line)
                                        for line in the_banner),
                                                      fillvalue=""))
    else:
        the_banner = "Welcome to Scapy (%s)" % conf.version
    if mybanner is not None:
        the_banner += "\n"
        the_banner += mybanner

    if IPYTHON:
        banner = the_banner + " using IPython %s\n" % IPython.__version__
        try:
            from traitlets.config.loader import Config
        except ImportError:
            log_loading.warning(
                "traitlets not available. Some Scapy shell features won't be "
                "available.")
            try:
                start_ipython(display_banner=False,
                              user_ns=SESSION,
                              exec_lines=["print(\"\"\"" + banner + "\"\"\")"])
            except Exception:
                code.interact(banner=the_banner, local=SESSION)
        else:
            cfg = Config()
            try:
                get_ipython
            except NameError:
                # Set "classic" prompt style when launched from run_scapy(.bat) files  # noqa: E501
                # Register and apply scapy color+prompt style
                apply_ipython_style(shell=cfg.TerminalInteractiveShell)
                cfg.TerminalInteractiveShell.confirm_exit = False
                cfg.TerminalInteractiveShell.separate_in = u''
            if int(IPython.__version__[0]) >= 6:
                cfg.TerminalInteractiveShell.term_title_format = "Scapy v" + conf.version  # noqa: E501
            else:
                cfg.TerminalInteractiveShell.term_title = False
            cfg.HistoryAccessor.hist_file = conf.histfile
            cfg.InteractiveShell.banner1 = banner
            # configuration can thus be specified here.
            try:
                start_ipython(config=cfg, user_ns=SESSION)
            except (AttributeError, TypeError):
                code.interact(banner=the_banner, local=SESSION)
    else:
        code.interact(banner=the_banner, local=SESSION)

    if conf.session:
        save_session(conf.session, SESSION)

    for k in GLOBKEYS:
        try:
            del (six.moves.builtins.__dict__[k])
        except Exception:
            pass
Exemplo n.º 20
0
 def test_set_update(self):
     c = Config()
     c.Containers.s.update({0, 1, 2})
     c.Containers.s.update({3})
     obj = Containers(config=c)
     self.assertEqual(obj.s, {'a', 0, 1, 2, 3})
Exemplo n.º 21
0
    def __init__(self,
                 argv=[],
                 user_ns=None,
                 user_global_ns=None,
                 cin=None,
                 cout=None,
                 cerr=None,
                 input_func=None):
        '''


    @param argv: Command line options for IPython
    @type argv: list
    @param user_ns: User namespace.
    @type user_ns: dictionary
    @param user_global_ns: User global namespace.
    @type user_global_ns: dictionary.
    @param cin: Console standard input.
    @type cin: IO stream
    @param cout: Console standard output.
    @type cout: IO stream
    @param cerr: Console standard error.
    @type cerr: IO stream
    @param input_func: Replacement for builtin raw_input()
    @type input_func: function
    '''
        io = IPython.utils.io
        if input_func:
            if parse_version(
                    IPython.release.version) >= parse_version("1.2.1"):
                IPython.terminal.interactiveshell.raw_input_original = input_func
            else:
                IPython.frontend.terminal.interactiveshell.raw_input_original = input_func
        if cin:
            io.stdin = io.IOStream(cin)
        if cout:
            io.stdout = io.IOStream(cout)
        if cerr:
            io.stderr = io.IOStream(cerr)

        # This is to get rid of the blockage that accurs during
        # IPython.Shell.InteractiveShell.user_setup()

        io.raw_input = lambda x: None

        os.environ['TERM'] = 'dumb'
        excepthook = sys.excepthook

        if parse_version(IPython.release.version) >= parse_version('4.0.0'):
            from traitlets.config.loader import Config
        else:
            from IPython.config.loader import Config
        cfg = Config()
        cfg.InteractiveShell.colors = "Linux"
        cfg.Completer.use_jedi = False

        # InteractiveShell's __init__ overwrites io.stdout,io.stderr with
        # sys.stdout, sys.stderr, this makes sure they are right
        #
        old_stdout, old_stderr = sys.stdout, sys.stderr
        sys.stdout, sys.stderr = io.stdout.stream, io.stderr.stream

        # InteractiveShell inherits from SingletonConfigurable, so use instance()
        #
        if parse_version(IPython.release.version) >= parse_version("1.2.1"):
            self.IP = IPython.terminal.embed.InteractiveShellEmbed.instance( \
                config=cfg, user_ns=user_ns)
        else:
            self.IP = IPython.frontend.terminal.embed.InteractiveShellEmbed.instance( \
                config=cfg, user_ns=user_ns)

        sys.stdout, sys.stderr = old_stdout, old_stderr

        self.IP.system = lambda cmd: self.shell(self.IP.var_expand(cmd),
                                                header='IPython system call: ')
        #                                            local_ns=user_ns)
        # global_ns=user_global_ns)
        # verbose=self.IP.rc.system_verbose)

        self.IP.raw_input = input_func
        sys.excepthook = excepthook
        self.iter_more = 0
        self.history_level = 0
        self.complete_sep = re.compile(r'[\s\{\}\[\]\(\)]')
        self.updateNamespace({'exit': lambda: None})
        self.updateNamespace({'quit': lambda: None})
        if parse_version(IPython.release.version) < parse_version("5.0.0"):
            self.IP.readline_startup_hook(self.IP.pre_readline)
        # Workaround for updating namespace with sys.modules
        #
        self.__update_namespace()

        # Avoid using input splitter when not really needed.
        # Perhaps it could work even before 5.8.0
        # But it definitely does not work any more with >= 7.0.0
        self.no_input_splitter = parse_version(
            IPython.release.version) >= parse_version('5.8.0')
        self.lines = []
        self.indent_spaces = ''
Exemplo n.º 22
0
 def test_dict_update(self):
     c = Config()
     c.Containers.d.update({'c': 'd'})
     c.Containers.d.update({'e': 'f'})
     obj = Containers(config=c)
     self.assertEqual(obj.d, {'a': 'b', 'c': 'd', 'e': 'f'})
Exemplo n.º 23
0
 def test_getitem_not_section(self):
     cfg = Config()
     self.assertNotIn('foo', cfg)
     foo = cfg['foo']
     assert isinstance(foo, LazyConfigValue)
     self.assertIn('foo', cfg)
Exemplo n.º 24
0
 def _config_default(self):
     if SomeSingleton.initialized():
         return SomeSingleton.instance().config
     return Config()
Exemplo n.º 25
0
 def test_builtin(self):
     c1 = Config()
     c1.format = "json"
Exemplo n.º 26
0
def load_file_config(config=None):
    if config is None:
        config = Config()
    file_config = Config()
    return file_config
Exemplo n.º 27
0
 def test_fromdictmerge(self):
     c1 = Config()
     c2 = Config({'Foo' : {'bar' : 1}})
     c1.merge(c2)
     self.assertEqual(c1.Foo.__class__, Config)
     self.assertEqual(c1.Foo.bar, 1)
Exemplo n.º 28
0
def interact(mydict=None, argv=None, mybanner=None, loglevel=logging.INFO):
    # type: (Optional[Any], Optional[Any], Optional[Any], int) -> None
    """
    Starts Scapy's console.
    """
    # We're in interactive mode, let's throw the DeprecationWarnings
    warnings.simplefilter("always")

    # Set interactive mode, load the color scheme
    from scapy.config import conf
    conf.interactive = True
    conf.color_theme = DefaultTheme()
    if loglevel is not None:
        conf.logLevel = loglevel

    STARTUP_FILE = DEFAULT_STARTUP_FILE
    PRESTART_FILE = DEFAULT_PRESTART_FILE

    session_name = None

    if argv is None:
        argv = sys.argv

    try:
        opts = getopt.getopt(argv[1:], "hs:Cc:Pp:d:H")
        for opt, parm in opts[0]:
            if opt == "-h":
                _usage()
            elif opt == "-H":
                conf.fancy_prompt = False
                conf.verb = 30
            elif opt == "-s":
                session_name = parm
            elif opt == "-c":
                STARTUP_FILE = parm
            elif opt == "-C":
                STARTUP_FILE = None
            elif opt == "-p":
                PRESTART_FILE = parm
            elif opt == "-P":
                PRESTART_FILE = None
            elif opt == "-d":
                conf.logLevel = max(1, conf.logLevel - 10)

        if len(opts[1]) > 0:
            raise getopt.GetoptError("Too many parameters : [%s]" %
                                     " ".join(opts[1]))

    except getopt.GetoptError as msg:
        log_loading.error(msg)
        sys.exit(1)

    # Reset sys.argv, otherwise IPython thinks it is for him
    sys.argv = sys.argv[:1]

    SESSION, GLOBKEYS = init_session(session_name, mydict)

    if STARTUP_FILE:
        _read_config_file(STARTUP_FILE, interactive=True)
    if PRESTART_FILE:
        _read_config_file(PRESTART_FILE, interactive=True)

    if not conf.interactive_shell or conf.interactive_shell.lower() in [
            "ipython", "auto"
    ]:
        try:
            import IPython
            from IPython import start_ipython
        except ImportError:
            log_loading.warning(
                "IPython not available. Using standard Python shell "
                "instead.\nAutoCompletion, History are disabled.")
            if WINDOWS:
                log_loading.warning("On Windows, colors are also disabled")
                conf.color_theme = BlackAndWhite()
            IPYTHON = False
        else:
            IPYTHON = True
    else:
        IPYTHON = False

    if conf.fancy_prompt:
        from scapy.utils import get_terminal_width
        mini_banner = (get_terminal_width() or 84) <= 75

        the_logo = [
            "                                      ",
            "                     aSPY//YASa       ",
            "             apyyyyCY//////////YCa    ",
            "            sY//////YSpcs  scpCY//Pp  ",
            " ayp ayyyyyyySCP//Pp           syY//C ",
            " AYAsAYYYYYYYY///Ps              cY//S",
            "         pCCCCY//p          cSSps y//Y",
            "         SPPPP///a          pP///AC//Y",
            "              A//A            cyP////C",
            "              p///Ac            sC///a",
            "              P////YCpc           A//A",
            "       scccccp///pSP///p          p//Y",
            "      sY/////////y  caa           S//P",
            "       cayCyayP//Ya              pY/Ya",
            "        sY/PsY////YCc          aC//Yp ",
            "         sc  sccaCY//PCypaapyCP//YSs  ",
            "                  spCPY//////YPSps    ",
            "                       ccaacs         ",
            "                                      ",
        ]

        # Used on mini screens
        the_logo_mini = [
            "      .SYPACCCSASYY  ",
            "P /SCS/CCS        ACS",
            "       /A          AC",
            "     A/PS       /SPPS",
            "        YP        (SC",
            "       SPS/A.      SC",
            "   Y/PACC          PP",
            "    PY*AYC        CAA",
            "         YYCY//SCYP  ",
        ]

        the_banner = [
            "",
            "",
            "   |",
            "   | Welcome to Scapy",
            "   | Version %s" % conf.version,
            "   |",
            "   | https://github.com/secdev/scapy",
            "   |",
            "   | Have fun!",
            "   |",
        ]

        if mini_banner:
            the_logo = the_logo_mini
            the_banner = [x[2:] for x in the_banner[3:-1]]
            the_banner = [""] + the_banner + [""]
        else:
            quote, author = choice(QUOTES)
            the_banner.extend(_prepare_quote(quote, author, max_len=39))
            the_banner.append("   |")
        banner_text = "\n".join(
            logo + banner
            for logo, banner in six.moves.zip_longest((
                conf.color_theme.logo(line)
                for line in the_logo), (conf.color_theme.success(line)
                                        for line in the_banner),
                                                      fillvalue=""))
    else:
        banner_text = "Welcome to Scapy (%s)" % conf.version
    if mybanner is not None:
        banner_text += "\n"
        banner_text += mybanner

    if IPYTHON:
        banner = banner_text + " using IPython %s\n" % IPython.__version__
        try:
            from traitlets.config.loader import Config
        except ImportError:
            log_loading.warning(
                "traitlets not available. Some Scapy shell features won't be "
                "available.")
            try:
                start_ipython(display_banner=False,
                              user_ns=SESSION,
                              exec_lines=["print(\"\"\"" + banner + "\"\"\")"])
            except Exception:
                code.interact(banner=banner_text, local=SESSION)
        else:
            cfg = Config()
            try:
                from IPython import get_ipython
                if not get_ipython():
                    raise ImportError
            except ImportError:
                # Set "classic" prompt style when launched from
                # run_scapy(.bat) files Register and apply scapy
                # color+prompt style
                apply_ipython_style(shell=cfg.TerminalInteractiveShell)
                cfg.TerminalInteractiveShell.confirm_exit = False
                cfg.TerminalInteractiveShell.separate_in = u''
            if int(IPython.__version__[0]) >= 6:
                cfg.TerminalInteractiveShell.term_title_format = ("Scapy v%s" %
                                                                  conf.version)
                # As of IPython 6-7, the jedi completion module is a dumpster
                # of fire that should be scrapped never to be seen again.
                cfg.Completer.use_jedi = False
            else:
                cfg.TerminalInteractiveShell.term_title = False
            cfg.HistoryAccessor.hist_file = conf.histfile
            cfg.InteractiveShell.banner1 = banner
            # configuration can thus be specified here.
            try:
                start_ipython(config=cfg, user_ns=SESSION)
            except (AttributeError, TypeError):
                code.interact(banner=banner_text, local=SESSION)
    else:
        code.interact(banner=banner_text, local=SESSION)

    if conf.session:
        save_session(conf.session, SESSION)

    for k in GLOBKEYS:
        try:
            del (six.moves.builtins.__dict__[k])
        except Exception:
            pass
Exemplo n.º 29
0
 def test_getattr_section(self):
     cfg = Config()
     self.assertNotIn('Foo', cfg)
     Foo = cfg.Foo
     assert isinstance(Foo, Config)
     self.assertIn('Foo', cfg)
Exemplo n.º 30
0
def kernel_config():
    """Create a config object with IPython kernel options"""
    import os

    from IPython.core.application import get_ipython_dir
    from spyderlib.config.main import CONF
    from spyderlib.utils.programs import is_module_installed
    from traitlets.config.loader import Config, load_pyconfig_files

    # ---- IPython config ----
    try:
        profile_path = osp.join(get_ipython_dir(), 'profile_default')
        ip_cfg = load_pyconfig_files(
            ['ipython_config.py', 'ipython_qtconsole_config.py'], profile_path)
    except:
        ip_cfg = Config()

    # ---- Spyder config ----
    spy_cfg = Config()

    # Until we implement Issue 1052
    spy_cfg.InteractiveShell.xmode = 'Plain'

    # Run lines of code at startup
    run_lines_o = CONF.get('ipython_console', 'startup/run_lines')
    if run_lines_o:
        spy_cfg.IPKernelApp.exec_lines = [
            x.strip() for x in run_lines_o.split(',')
        ]
    else:
        spy_cfg.IPKernelApp.exec_lines = []

    # Pylab configuration
    mpl_backend = None
    mpl_installed = is_module_installed('matplotlib')
    pylab_o = CONF.get('ipython_console', 'pylab')
    external_interpreter = \
                   os.environ.get('EXTERNAL_INTERPRETER', '').lower() == "true"

    if mpl_installed and pylab_o:
        # Get matplotlib backend
        if not external_interpreter:
            if os.environ["QT_API"] == 'pyqt5':
                qt_backend = 'qt5'
            else:
                qt_backend = 'qt'

            backend_o = CONF.get('ipython_console', 'pylab/backend', 0)
            backends = {
                0: 'inline',
                1: qt_backend,
                2: qt_backend,
                3: 'osx',
                4: 'gtk',
                5: 'wx',
                6: 'tk'
            }
            mpl_backend = backends[backend_o]
        else:
            mpl_backend = 'inline'

        # Automatically load Pylab and Numpy, or only set Matplotlib
        # backend
        autoload_pylab_o = CONF.get('ipython_console', 'pylab/autoload')
        if autoload_pylab_o:
            spy_cfg.IPKernelApp.exec_lines.append(
                "%pylab {0}".format(mpl_backend))
        else:
            spy_cfg.IPKernelApp.exec_lines.append(
                "%matplotlib {0}".format(mpl_backend))

        # Inline backend configuration
        if backends[backend_o] == 'inline':
            # Figure format
            format_o = CONF.get('ipython_console',
                                'pylab/inline/figure_format', 0)
            formats = {0: 'png', 1: 'svg'}
            spy_cfg.InlineBackend.figure_format = formats[format_o]

            # Resolution
            spy_cfg.InlineBackend.rc = {
                'figure.figsize': (6.0, 4.0),
                'savefig.dpi': 72,
                'font.size': 10,
                'figure.subplot.bottom': .125,
                'figure.facecolor': 'white',
                'figure.edgecolor': 'white'
            }
            resolution_o = CONF.get('ipython_console',
                                    'pylab/inline/resolution')
            spy_cfg.InlineBackend.rc['savefig.dpi'] = resolution_o

            # Figure size
            width_o = float(CONF.get('ipython_console', 'pylab/inline/width'))
            height_o = float(CONF.get('ipython_console',
                                      'pylab/inline/height'))
            spy_cfg.InlineBackend.rc['figure.figsize'] = (width_o, height_o)

    # Run a file at startup
    use_file_o = CONF.get('ipython_console', 'startup/use_run_file')
    run_file_o = CONF.get('ipython_console', 'startup/run_file')
    if use_file_o and run_file_o:
        spy_cfg.IPKernelApp.file_to_run = run_file_o

    # Autocall
    autocall_o = CONF.get('ipython_console', 'autocall')
    spy_cfg.ZMQInteractiveShell.autocall = autocall_o

    # To handle the banner by ourselves in IPython 3+
    spy_cfg.ZMQInteractiveShell.banner1 = ''

    # Greedy completer
    greedy_o = CONF.get('ipython_console', 'greedy_completer')
    spy_cfg.IPCompleter.greedy = greedy_o

    # Sympy loading
    sympy_o = CONF.get('ipython_console', 'symbolic_math')
    if sympy_o:
        lines = sympy_config(mpl_backend)
        spy_cfg.IPKernelApp.exec_lines.append(lines)

    # Merge IPython and Spyder configs. Spyder prefs will have prevalence
    # over IPython ones
    ip_cfg._merge(spy_cfg)
    return ip_cfg