Exemplo n.º 1
0
def interact(session=False, apk=None):
    """
    Start an interactive shell
    :param session:
    :param apk:
    :return:
    """
    from androguard.core.androconf import ANDROGUARD_VERSION, CONF
    from IPython.terminal.embed import InteractiveShellEmbed
    from traitlets.config import Config

    from androguard.misc import init_print_colors, AnalyzeAPK
    from androguard.session import Session

    if session:
        CONF["SESSION"] = Session(export_ipython=True)

    if apk:
        print("Loading apk {}...".format(os.path.basename(apk)))
        print("Please be patient, this might take a while.")
        # TODO we can export fancy aliases for those as well...
        a, d, dx = AnalyzeAPK(apk)

    cfg = Config()
    _version_string = "Androguard version {}".format(ANDROGUARD_VERSION)
    ipshell = InteractiveShellEmbed(
        config=cfg, banner1="{} started".format(_version_string))
    init_print_colors()
    ipshell()
Exemplo n.º 2
0
def insert_ipython(num_up=1):
    """
    Placed inside a function, this will insert an IPython interpreter at that
    current location.  This will enabled detailed inspection of the current
    exeuction environment, as well as (optional) modification of that environment.
    *num_up* refers to how many frames of the stack get stripped off, and
    defaults to 1 so that this function itself is stripped off.
    """
    import IPython
    from IPython.terminal.embed import InteractiveShellEmbed
    try:
        from traitlets.config.loader import Config
    except ImportError:
        from IPython.config.loader import Config

    frame = inspect.stack()[num_up]
    loc = frame[0].f_locals.copy()
    glo = frame[0].f_globals
    dd = dict(fname=frame[3], filename=frame[1], lineno=frame[2])
    cfg = Config()
    cfg.InteractiveShellEmbed.local_ns = loc
    cfg.InteractiveShellEmbed.global_ns = glo
    IPython.embed(config=cfg, banner2=__header % dd)
    ipshell = InteractiveShellEmbed(config=cfg)

    del ipshell
Exemplo n.º 3
0
 def runPlugin(self):
     '''
     Runs the plugin.
     '''
     try:
         get_ipython
     except NameError:
         nested = 0
         cfg = Config()
         prompt_config = cfg.PromptManager
         prompt_config.in_template = 'Tortazo Plugin <%s> : ' % (
             self.pluginLoaded)
         prompt_config.in2_template = "Type 'self.help()' to get information about the functions available in this plugin :"
     else:
         cfg = Config()
         nested = 1
     try:
         #Runs from interpreter, so the exceptions and stuff like that, must be handled from the plugin itself.
         self.runFromInterpreter = True
         self.tortazoShell = InteractiveShellEmbed(
             config=cfg,
             banner1='Loading Tortazo plugin interpreter... ',
             banner2=
             "Plugin %s loaded successfully! Type self.help() to get information about this plugin and exit() to finish the execution. "
             % (self.pluginLoaded),
             exit_msg='Leaving Tortazo plugin interpreter.')
         self.tortazoShell()
     except PluginException as pluginExc:
         print "[-] Exception raised executing the plugin. Please, check the arguments used in the function called. Details below."
         print "Message: %s " % (pluginExc.getMessage())
         print "Plugin: %s " % (pluginExc.getPlugin())
         print "Method: %s " % (pluginExc.getMethod())
         print "Trace: %s " % (pluginExc.getTrace())
    def run_shell(self, atomspace):
        from opencog.atomspace import types, Atom, Handle, TruthValue
        namespace = locals().copy()
        try:
            import threading
            import IPython
            from IPython.config.loader import Config

            # Configure the prompts.
            cfg = Config()
            cfg.PromptManager.in_template = "py[\\#]> "
            cfg.PromptManager.out_template = "py[\\#]: "

            # Create an instance of the embeddable shell.
            from IPython.terminal.embed import InteractiveShellEmbed
            banner = "OpenCog IPython Shell. Access the main AtomSpace as 'atomspace'."
            exit_message = "Leaving Interpreter, back to program."
            ipython_shell = InteractiveShellEmbed(config=cfg,
                                                  user_ns=namespace,
                                                  banner1=banner,
                                                  exit_msg=exit_message)

            # Launch the shell in a new thread so the request doesn't hang
            # the shell that launched this shell.
            shell_thread = threading.Thread(None, ipython_shell, "ipython", ())
            shell_thread.start()
        except Exception, e:
            print e
Exemplo n.º 5
0
def launch_creature(name, vrep):
    """
    Loads creature's class and launches a shell.
    Note: name is case insensitive.
    """
    ns = load_poppy_creatures()
    cls = None
    for x in ns:
        # Strips leading 'Poppy'
        if x.__name__[5:].lower() == name.lower():
            cls = x

    if cls is None:
        sys.stderr.write("Creature not found : {}\n".format(name))
        sys.exit(1)

    poppy_args = {}
    if vrep:
        poppy_args['simulator'] = 'vrep'

    with open(resource_filename('poppy', 'logo.ascii')) as f:
        poppy_welcome = f.read()

    poppy_welcome += 'Poppy creature: {}'.format(name)

    ns = {'poppy': cls(**poppy_args)}
    banner = 'poppy : {}'.format(cls.__name__)
    cfg = ipConfig()
    cfg.TerminalInteractiveShell.confirm_exit = False
    shell = InteractiveShellEmbed(config=cfg,
                                  user_ns=ns,
                                  banner2=poppy_welcome)
    shell()
Exemplo n.º 6
0
def askip(pylab=False,
          enter="Launch iPython?",
          exit="Continuing...",
          default="no"):
    """Ask for ipython, returning a callable to start the shell, or do nothing.
    
    To ensure that this method is run in the correct scope, it should be called like this::
        
        >>> a = 10
        >>> askip()()
        >>> b = 20 + a
        
    :param bool pylab: Whether to set up interactive pylab plotting.
    :param str enter: Message used as the question to the user.
    :param str exit: Message used when the user exits the shell.
    :param str default: The default answer ("yes" or "no")
    :returns: A function which either does nothing, or starts an iPython shell.
    """
    from IPython.terminal.embed import InteractiveShellEmbed
    if query_yes_no(enter, default=default):
        if pylab:
            import matplotlib.pyplot as plt
            plt.ion()
        return InteractiveShellEmbed(exit_msg=exit)
    else:
        return lambda: None  #No-op callable.
Exemplo n.º 7
0
def load_and_run_tshell():
    """Launch a shell for a thrift service."""
    parser = argparse.ArgumentParser(
        description=
        "Open a shell for a Thrift service with app configuration loaded.",
        formatter_class=argparse.RawDescriptionHelpFormatter,
    )

    parser.add_argument("--debug",
                        action="store_true",
                        default=False,
                        help="enable extra-verbose debug logging")
    parser.add_argument(
        "--app-name",
        default="main",
        metavar="NAME",
        help="name of app to load from config_file (default: main)")
    parser.add_argument("config_file",
                        type=argparse.FileType("r"),
                        help="path to a configuration file")

    args = parser.parse_args(sys.argv[1:])
    config = read_config(args.config_file,
                         server_name=None,
                         app_name=args.app_name)
    logging.basicConfig(level=logging.INFO)

    env = dict()
    env_banner = {
        'app': "This project's app instance",
        'context': "The context for this shell instance's span",
    }

    app = make_app(config.app)
    env['app'] = app

    span = app.baseplate.make_server_span(RequestContext(), 'shell')
    env['context'] = span.context

    if config.tshell and 'setup' in config.tshell:
        setup = _load_factory(config.tshell['setup'])
        setup(env, env_banner)

    # generate banner text
    banner = "Available Objects:\n"
    for var in sorted(env_banner.keys()):
        banner += '\n  %-12s %s' % (var, env_banner[var])

    try:
        # try to use IPython if possible
        from IPython.terminal.embed import InteractiveShellEmbed
        shell = InteractiveShellEmbed(banner2=banner)
        shell(local_ns=env, global_ns={})
    except ImportError:
        import code
        newbanner = "Baseplate Interactive Shell\nPython {}\n\n".format(
            sys.version)
        banner = newbanner + banner
        shell = code.InteractiveConsole(locals=env)
        shell.interact(banner)
Exemplo n.º 8
0
def start_shell(algorithm, algomodule):
    algomodule['context'] = algorithm
    algomodule['data'] = BarData(algorithm.data_portal,
                                 algorithm.data_frequency)
    algorithm.on_dt_changed(pd.Timestamp.utcnow().floor('1min'))
    algomodule['data'].datetime = algorithm.datetime
    InteractiveShellEmbed()('*** pylivetrader shell ***', local_ns=algomodule)
Exemplo n.º 9
0
def main(path_to_serialized_model):
    print('Loading: ' + str(path_to_serialized_model))
    network = fieldnetwork.deserialize_network(path_to_serialized_model)
    store_client = StoreHandler()
    api = API(network, store_client)
    ip_shell = InteractiveShellEmbed(banner1=init_banner, exit_msg=exit_banner)
    ip_shell()
Exemplo n.º 10
0
    def embed(self):
        if not self.preview:
            # If the scene is just being
            # written, ignore embed calls
            return
        self.stop_skipping()
        self.linger_after_completion = False
        self.update_frame()

        # Save scene state at the point of embedding
        self.save_state()

        from IPython.terminal.embed import InteractiveShellEmbed
        shell = InteractiveShellEmbed()
        # Have the frame update after each command
        shell.events.register('post_run_cell',
                              lambda *a, **kw: self.update_frame())
        # Use the locals of the caller as the local namespace
        # once embedded, and add a few custom shortcuts
        local_ns = inspect.currentframe().f_back.f_locals
        local_ns["touch"] = self.interact
        for term in ("play", "wait", "add", "remove", "clear", "save_state",
                     "restore"):
            local_ns[term] = getattr(self, term)
        log.info(
            "Tips: Now the embed iPython terminal is open. But you can't interact with"
            " the window directly. To do so, you need to type `touch()` or `self.interact()`"
        )
        shell(local_ns=local_ns, stack_depth=2)
        # End scene when exiting an embed.
        raise EndSceneEarlyException()
Exemplo n.º 11
0
    def embed(self):
        if not self.preview:
            # If the scene is just being
            # written, ignore embed calls
            return
        self.stop_skipping()
        self.linger_after_completion = False
        self.update_frame()

        from IPython.terminal.embed import InteractiveShellEmbed

        shell = InteractiveShellEmbed()
        # Have the frame update after each command
        shell.events.register("post_run_cell",
                              lambda *a, **kw: self.update_frame())
        # Use the locals of the caller as the local namespace
        # once embeded, and add a few custom shortcuts
        local_ns = inspect.currentframe().f_back.f_locals
        local_ns["touch"] = self.interact
        for term in ("play", "wait", "add", "remove", "clear", "save_state",
                     "restore"):
            local_ns[term] = getattr(self, term)
        shell(local_ns=local_ns, stack_depth=2)
        # End scene when exiting an embed.
        raise EndSceneEarlyException()
Exemplo n.º 12
0
def main():
    try:
        get_ipython
    except NameError:
        pass
    else:
        exit("Running ipython inside ipython isn't supported. :(")

    options, basic_auth, oauth = get_config()

    if basic_auth:
        basic_auth = (basic_auth['username'], basic_auth['password'])

    if oauth.get('oauth_dance') is True:
        oauth = oauth_dance(options['server'], oauth['consumer_key'],
                            oauth['key_cert'], oauth['print_tokens'],
                            options['verify'])
    elif not all((oauth.get('access_token'), oauth.get('access_token_secret'),
                  oauth.get('consumer_key'), oauth.get('key_cert'))):
        oauth = None

    jira = JIRA(options=options, basic_auth=basic_auth, oauth=oauth)

    import IPython
    # The top-level `frontend` package has been deprecated since IPython 1.0.
    if IPython.version_info[0] >= 1:
        from IPython.terminal.embed import InteractiveShellEmbed
    else:
        from IPython.frontend.terminal.embed import InteractiveShellEmbed

    ipshell = InteractiveShellEmbed(banner1='<JIRA Shell ' + __version__ +
                                    ' (' + jira.client_info() + ')>')
    ipshell("*** JIRA shell active; client is in 'jira'."
            ' Press Ctrl-D to exit.')
Exemplo n.º 13
0
def main_shell(args):
    from IPython.terminal.embed import InteractiveShellEmbed
    import portage
    mdb = MultiDb(args.portdir, args.profile)
    banner = "Use the \"mdb\" object to explore the Portage databases."
    ipshell = InteractiveShellEmbed(banner1=banner)
    ipshell()
Exemplo n.º 14
0
    def run(self, arguments, settings, app):
        app_settings["root_user"]["password"] = TESTING_SETTINGS["root_user"][
            "password"]
        root = get_utility(IApplication, name="root")
        request = get_mocked_request()
        login()
        helpers = ShellHelpers(app, root, request)
        task_vars.request.set(request)
        use_db = helpers.use_db  # noqa
        use_container = helpers.use_container  # noqa
        commit = helpers.commit  # noqa
        abort = helpers.abort  # noqa
        setup = helpers.setup_context  # noqa

        try:
            from IPython.terminal.embed import InteractiveShellEmbed  # type: ignore
            from traitlets.config.loader import Config  # type: ignore
        except ImportError:
            sys.stderr.write("You must install ipython for the "
                             "shell command to work.\n"
                             "Use `pip install ipython` to install ipython.\n")
            return 1

        cfg = Config()
        loop = self.get_loop()
        banner = loop.run_until_complete(self.get_banner())
        ipshell = InteractiveShellEmbed(config=cfg, banner1=banner)
        ipshell()
Exemplo n.º 15
0
def interact():
    cfg = Config()
    ipshell = InteractiveShellEmbed(config=cfg,
                                    banner1="Androlyze version %s" %
                                    ANDROGUARD_VERSION)
    init_print_colors()
    ipshell()
Exemplo n.º 16
0
        def shell(ipython: bool = True):
            """ Run the application shell.

            :param ipython: Use IPython as shell

            """
            app.loop.run_until_complete(app.start())

            banner = '\nInteractive Muffin Shell\n'
            namespace = app.cfg.MANAGE_SHELL
            if callable(namespace):
                namespace = namespace()
            banner += "Loaded objects: %s" % list(namespace.keys())
            if ipython:
                try:
                    from IPython.terminal.embed import InteractiveShellEmbed
                    sh = InteractiveShellEmbed(banner1=banner)
                except ImportError:
                    pass
                else:
                    sh(global_ns={}, local_ns=namespace)
                    return

            from code import interact
            interact(banner, local=namespace)

            app.loop.run_until_complete(app.finish())
Exemplo n.º 17
0
def main():

    try:
        try:
            get_ipython
        except NameError:
            pass
        else:
            sys.exit("Running ipython inside ipython isn't supported. :(")

        options, basic_auth, oauth, kerberos_auth = get_config()

        if basic_auth:
            basic_auth = handle_basic_auth(auth=basic_auth, server=options["server"])

        if oauth.get("oauth_dance") is True:
            oauth = oauth_dance(
                options["server"],
                oauth["consumer_key"],
                oauth["key_cert"],
                oauth["print_tokens"],
                options["verify"],
            )
        elif not all(
            (
                oauth.get("access_token"),
                oauth.get("access_token_secret"),
                oauth.get("consumer_key"),
                oauth.get("key_cert"),
            )
        ):
            oauth = None

        use_kerberos = kerberos_auth.get("use_kerberos", False)
        del kerberos_auth["use_kerberos"]

        jira = JIRA(
            options=options,
            basic_auth=basic_auth,
            kerberos=use_kerberos,
            kerberos_options=kerberos_auth,
            oauth=oauth,
        )

        import IPython

        # The top-level `frontend` package has been deprecated since IPython 1.0.
        if IPython.version_info[0] >= 1:
            from IPython.terminal.embed import InteractiveShellEmbed
        else:
            from IPython.frontend.terminal.embed import InteractiveShellEmbed

        ip_shell = InteractiveShellEmbed(
            banner1="<Jira Shell " + __version__ + " (" + jira.client_info() + ")>"
        )
        ip_shell("*** Jira shell active; client is in 'jira'." " Press Ctrl-D to exit.")
    except Exception as e:
        print(e, file=sys.stderr)
        return 2
Exemplo n.º 18
0
def interact():
    CONF["SESSION"] = Session(True)
    cfg = Config()
    ipshell = InteractiveShellEmbed(config=cfg,
                                    banner1="Androguard version %s" %
                                    ANDROGUARD_VERSION)
    init_print_colors()
    ipshell()
Exemplo n.º 19
0
 def shell(self, banner1='-- Augur Shell --', **kwargs):
     from IPython.terminal.embed import InteractiveShellEmbed
     if not self.__shell_config:
         from augur.util import init_shell_config
         self.__shell_config = init_shell_config()
     return InteractiveShellEmbed(config=self.__shell_config,
                                  banner1=banner1,
                                  **kwargs)
Exemplo n.º 20
0
def start():
    ip_shell = InteractiveShellEmbed()

    present_working_directory = ip_shell.magic("%pwd")
    print(present_working_directory)
    os.system("cd "+present_working_directory)
    temp=os.system(cmd)  
    print(temp)
Exemplo n.º 21
0
def test_ipython(tmp_path):
    os.chdir(str(tmp_path))
    dotenv_file = tmp_path / '.env'
    dotenv_file.write_text("MYNEWVALUE=q1w2e3\n")
    ipshell = InteractiveShellEmbed()
    ipshell.magic("load_ext dotenv")
    ipshell.magic("dotenv")
    assert os.environ["MYNEWVALUE"] == 'q1w2e3'
Exemplo n.º 22
0
def ipsh():
    """
    Debugar código pontualmente via seção independente do IPython.

    Invoque a função ``ocnpylib.ipsh()`` em qualquer lugar do script a
    partir do qual deseja debugar o respectivo código. Será carregado um
    shell do IPython incorporado ao ambiente. Isto permite avaliar
    dinamicamente o estado do código, operar e analizar variáveis, etc.

    **Notas:**

    + Enquanto no shell, quaisquer mudanças realizadas aos valores já
      atribuídos não se propagam de volta ao código sob execução. Logo,
      é seguro modificar seus valores sem risco de quebra do código.

    + Instâncias do ``InteractiveShellEmbed`` não imprimem mensagens nem
      painéis padrões do sistema. O painel do IPython (o qual pode
      conter mensagens de inicialização) está disponível via
      ``get_ipython().banner``.

    + Toda vez inicializada, a instância do ``InteractiveShellEmbed``
      imprime: - um painel global; - cabeçalho específico da chamada, o
      qual pode ser usado para identificar onde o fluxo de execução do
      shell está iniciando; - uma mensagem de saída.

    + Ambos painel de inicialização e mensagem de saída são ``None`` por
      padrão e podem ser configurados na instanciação do construtor ou
      há qualquer momento com os atributos do objeto ``banner`` e
      ``exit_msg`` respectivamente.

    + O shell pode ser colocado em modo *dummy* globalmente ou em bases
      por chamada, permitindo o controle fino do debug sem a necessidade
      de alterar o código original.

    """

    # Configuração do prompt para identificação de aninhamento do shell.
    cfg = Config()
    cfg.TerminalInteractiveShell.prompts_class = MyPrompt

    # Mensagens informativas de inicialização e saída do shell.
    banner_msg = ("\n**Embended Interpreter:\n" +
                  "Hit Ctrl-D to exit interpreter and continue program.\n" +
                  "Note that if you use %kill_embedded, you can fully" +
                  " deactivate\n" +
                  "This embedded instance so it will never turn on again")
    exit_msg = '**Leaving Embended Interpreter'
    ipshell = InteractiveShellEmbed(config=cfg,
                                    banner1=banner_msg,
                                    exit_msg=exit_msg)

    frame = inspect.currentframe().f_back
    msg = ("Debuging at " +
           "{0.f_code.co_filename} at line {0.f_lineno}".format(frame))

    # Retorno de um nível! Necessário pela chamada do ipshell dentro da
    # função ipsh().
    ipshell(msg, stack_depth=2)
Exemplo n.º 23
0
 def handle(self, *args, **options):
     modules = ('mainapp.models', )
     for module in modules:
         m = __import__(module, fromlist='non-empty')
         for a in m.__dict__:
             v = getattr(m, a)
             if hasattr(v, '__base__') and issubclass(v, Model):
                 globals()[a] = v
     InteractiveShellEmbed()()
Exemplo n.º 24
0
def main(args):
    shell = InteractiveShellEmbed()
    geology = Geology(get_input(args.YEAR, args.DAY))
    print(sum(geology.traverse(3, 1)))
    slopes = [(1, 1), (3, 1), (5, 1), (7, 1), (1, 2)]
    prod = 1
    for m in slopes:
        prod *= sum(geology.traverse(*m))
    print(prod)
Exemplo n.º 25
0
def ipsh():
    ipshell = InteractiveShellEmbed(config=cfg, banner1=banner_msg, exit_msg=exit_msg)

    frame = inspect.currentframe().f_back
    msg   = 'Stopped at {0.f_code.co_filename} at line {0.f_lineno}'.format(frame)

    # Go back one level!
    # This is needed because the call to ipshell is inside the function ipsh()
    ipshell(msg,stack_depth=2)
Exemplo n.º 26
0
def main():
    # workaround for avoiding UnicodeEncodeError when printing exceptions
    # containing unicode on py2
    if sys.version_info[0] < 3 and sys.getdefaultencoding() != 'utf-8':
        # without reload print would fail even if sys.stdin.encoding
        # would report utf-8
        # see: https://stackoverflow.com/a/23847316/99834
        stdin, stdout, stderr = sys.stdin, sys.stdout, sys.stderr
        reload(sys)
        sys.stdin, sys.stdout, sys.stderr = stdin, stdout, stderr
        sys.setdefaultencoding(os.environ.get('PYTHONIOENCODING', 'utf-8'))

    try:
        try:
            get_ipython
        except NameError:
            pass
        else:
            sys.exit("Running ipython inside ipython isn't supported. :(")

        options, basic_auth, oauth, kerberos_auth = get_config()

        if basic_auth:
            basic_auth = (basic_auth['username'], basic_auth['password'])

        if oauth.get('oauth_dance') is True:
            oauth = oauth_dance(options['server'], oauth['consumer_key'],
                                oauth['key_cert'], oauth['print_tokens'],
                                options['verify'])
        elif not all(
            (oauth.get('access_token'), oauth.get('access_token_secret'),
             oauth.get('consumer_key'), oauth.get('key_cert'))):
            oauth = None

        use_kerberos = kerberos_auth.get('use_kerberos', False)
        del kerberos_auth['use_kerberos']

        jira = JIRA(options=options,
                    basic_auth=basic_auth,
                    kerberos=use_kerberos,
                    kerberos_options=kerberos_auth,
                    oauth=oauth)

        import IPython
        # The top-level `frontend` package has been deprecated since IPython 1.0.
        if IPython.version_info[0] >= 1:
            from IPython.terminal.embed import InteractiveShellEmbed
        else:
            from IPython.frontend.terminal.embed import InteractiveShellEmbed

        ip_shell = InteractiveShellEmbed(banner1='<JIRA Shell ' + __version__ +
                                         ' (' + jira.client_info() + ')>')
        ip_shell("*** JIRA shell active; client is in 'jira'."
                 ' Press Ctrl-D to exit.')
    except Exception as e:
        print(e, file=sys.stderr)
        return 2
    def ipsh():
        """
        Start a regular IPython session at any point in your program.

        This allows you to evaluate dynamically the state of your code,
        operate with your variables, analyze them, etc. Note however that
        any changes you make to values while in the shell do not propagate
        back to the running code, so it is safe to modify your values because
        you won’t break your code in bizarre ways by doing so.

        Usage
        _____
        Put ipsh() anywhere in your code where you want it to open.
        This code will load an embeddable IPython shell always with no changes
        for nested embededings.

        Notes
        _____
        + InteractiveShellEmbed instances don't print the standard system
        banner and messages. The IPython banner (which actually may contain
        initialization messages) is available as get_ipython().banner in case
        you want it.

        + InteractiveShellEmbed instances print the following information
        everytime they start:
        - A global startup banner.
        - A call-specific header string, which you can use to indicate where
        in the execution flow the shell is starting.

        + They also print an exit message every time they exit.

        + Both the startup banner and the exit message default to None, and can
        be set either at the instance constructor or at any other time with the
        by setting the banner and exit_msg attributes.

        + The shell instance can be also put in 'dummy' mode globally or on a
        per-call basis. This gives you fine control for debugging without having
        to change code all over the place.

        """
        # Configure the prompt so that I know I am in a nested (embedded) shell
        cfg = Config()
        cfg.TerminalInteractiveShell.prompts_class = MyPrompt

        # Messages displayed when I drop into and exit the shell.
        banner_msg = ("\n**Dropping into Embended Interpreter:\n"
                      "Hit Ctrl-D to exit interpreter and continue program.\n")
        exit_msg = '**Leaving Embended Interpreter, back to program'
        ipshell = InteractiveShellEmbed(config=cfg, banner1=banner_msg,
                                        exit_msg=exit_msg)

        frame = inspect.currentframe().f_back
        msg = 'Debuging at line {0.f_lineno}'.format(frame)
        # Go back one level!
        # This is needed because the call to ipshell is
        # inside the function ipsh()
        ipshell(msg, stack_depth=2)
Exemplo n.º 28
0
def test_ipython():
    tmpdir = os.path.realpath(tempfile.mkdtemp())
    os.chdir(tmpdir)
    filename = os.path.join(tmpdir, '.env')
    with open(filename, 'w') as f:
        f.write("MYNEWVALUE=q1w2e3\n")
    ipshell = InteractiveShellEmbed()
    ipshell.magic("load_ext dotenv")
    ipshell.magic("dotenv")
    assert os.environ["MYNEWVALUE"] == 'q1w2e3'
Exemplo n.º 29
0
    def run(self):
        """
        Args:
            None

        Returns:
            None
        """
        ipshell = InteractiveShellEmbed(config=self.config, banner1="")
        ipshell()
Exemplo n.º 30
0
def test_ipython_override(tmp_path):
    from IPython.terminal.embed import InteractiveShellEmbed
    os.chdir(str(tmp_path))
    dotenv_file = tmp_path / '.env'
    os.environ["MYNEWVALUE"] = "OVERRIDE"
    dotenv_file.write_text("MYNEWVALUE=q1w2e3\n")
    ipshell = InteractiveShellEmbed()
    ipshell.magic("load_ext dotenv")
    ipshell.magic("dotenv -o")
    assert os.environ["MYNEWVALUE"] == 'q1w2e3'