Python code.interact() Examples

The following are 30 code examples of code.interact(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module code , or try the search function .
Example #1
Source File: scripts.py    From AnyBlok with Mozilla Public License 2.0 8 votes vote down vote up
def anyblok_interpreter():
    """Execute a script or open an interpreter
    """
    registry = anyblok.start('interpreter')
    if registry:
        registry.commit()
        python_script = Configuration.get('python_script')
        if python_script:
            with open(python_script, "r") as fh:
                exec(fh.read(), None, locals())
        else:
            try:
                from IPython import embed
                embed()
            except ImportError:
                import code
                code.interact(local=locals()) 
Example #2
Source File: auto2to3.py    From kgsgo-dataset-preprocessor with Mozilla Public License 2.0 7 votes vote down vote up
def main():
    parser = argparse.ArgumentParser()
    parser.add_argument('--package', action='append')
    parser.add_argument('--dir', action='append')
    parser.add_argument('-m', action='store', metavar='MODULE')
    args, rest = parser.parse_known_args()
    if args.package:
        PACKAGES.extend(args.package)
    if args.dir:
        DIRS.extend(os.path.abspath(d) for d in args.dir)
    if not PACKAGES and not DIRS:
        DIRS.append(os.getcwd())
    if args.m:
        sys.argv[1:] = rest
        runpy.run_module(args.m, run_name='__main__', alter_sys=True)
    elif rest:
        sys.argv = rest
        converted = maybe_2to3(rest[0])
        with open(converted) as f:
            new_globals = dict(__name__='__main__',
                               __file__=rest[0])
            exec(f.read(), new_globals)
    else:
        import code
        code.interact() 
Example #3
Source File: main.py    From pg_simple with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_basic_functions(self):
        import code
        import doctest
        import sys

        db = pg_simple.PgSimple(self.pool)
        if sys.argv.count('--interact'):
            db.log = sys.stdout
            code.interact(local=locals())
        else:
            try:
                # Setup tables
                self._drop_tables(db)
                self._create_tables(db, fill=True)
                # Run tests
                doctest.testmod(optionflags=doctest.ELLIPSIS)
            finally:
                # Drop tables
                self._drop_tables(db)
        self.assertEqual(True, True) 
Example #4
Source File: main.py    From pg_simple with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_connection_auto_commit(self):
        import code
        import sys

        with pg_simple.PgSimple(self.pool) as db:
            if sys.argv.count('--interact'):
                db.log = sys.stdout
                code.interact(local=locals())
            else:
                self._drop_tables(db)
                self._create_tables(db, fill=True)

        with pg_simple.PgSimple(self.pool) as db:
            try:
                self._check_table(db, 'pg_t1')
            finally:
                self._drop_tables(db) 
Example #5
Source File: ipython.py    From rekall with GNU General Public License v2.0 6 votes vote down vote up
def NativePythonSupport(user_session):
    """Launch the rekall session using the native python interpreter.

    Returns:
      False if we failed to use IPython. True if the session was run and exited.
    """
    # If the ipython shell is not available, we can use the native python shell.
    import code

    # Try to enable tab completion
    try:
        import rlcompleter, readline  # pylint: disable=unused-variable
        readline.parse_and_bind("tab: complete")
    except ImportError:
        pass

    # Prepare the session for running within the native python interpreter.
    user_session.PrepareLocalNamespace()
    code.interact(banner=constants.BANNER, local=user_session.locals) 
Example #6
Source File: inference.py    From pykg2vec with MIT License 6 votes vote down vote up
def main():
    # getting the customized configurations from the command-line arguments.
    args = KGEArgParser().get_args(sys.argv[1:])

    # Preparing data and cache the data for later usage
    knowledge_graph = KnowledgeGraph(dataset=args.dataset_name, custom_dataset_path=args.dataset_path)
    knowledge_graph.prepare_data()

    # Extracting the corresponding model config and definition from Importer().
    config_def, model_def = Importer().import_model_config(args.model_name.lower())
    config = config_def(args)
    model = model_def(config)

    # Create, Compile and Train the model. While training, several evaluation will be performed.
    trainer = Trainer(model, config)
    trainer.build_model()
    trainer.train_model()
    
    #can perform all the inference here after training the model
    trainer.enter_interactive_mode()
    
    code.interact(local=locals())

    trainer.exit_interactive_mode() 
Example #7
Source File: jsonrpc_shell_base.py    From mobly with Apache License 2.0 6 votes vote down vote up
def start_console(self):
        # Set up initial console environment
        console_env = {
            'ad': self._ad,
            'pprint': pprint.pprint,
        }

        # Start the services
        self._start_services(console_env)

        # Start the console
        console_banner = self._get_banner(self._ad.serial)
        code.interact(banner=console_banner, local=console_env)

        # Tear everything down
        self._ad.services.stop_all() 
Example #8
Source File: cli.py    From nightmare with GNU General Public License v2.0 6 votes vote down vote up
def do_python(self, line):
        """
        Start an interactive python interpreter. The namespace of the
        interpreter is updated with expression nicities.  You may also
        specify a line of python code as an argument to be exec'd without
        beginning an interactive python interpreter on the controlling
        terminal.

        Usage: python [pycode]
        """
        locals = self.getExpressionLocals()
        if len(line) != 0:
            cobj = compile(line, 'cli_input', 'exec')
            exec(cobj, locals)
        else:
            code.interact(local=locals) 
Example #9
Source File: __init__.py    From nightmare with GNU General Public License v2.0 6 votes vote down vote up
def interact(pid=0,server=None,trace=None):

    """
    Just a cute and dirty way to get a tracer attached to a pid
    and get a python interpreter instance out of it.
    """

    global remote
    remote = server

    if trace == None:
        trace = getTrace()
        if pid:
            trace.attach(pid)

    mylocals = {}
    mylocals["trace"] = trace

    code.interact(local=mylocals) 
Example #10
Source File: interactive.py    From PyDev.Debugger with Eclipse Public License 1.0 6 votes vote down vote up
def _spawn_python_shell(self, arg):
        import winappdbg
        banner = ('Python %s on %s\nType "help", "copyright", '
                 '"credits" or "license" for more information.\n')
        platform = winappdbg.version.lower()
        platform = 'WinAppDbg %s' % platform
        banner = banner % (sys.version, platform)
        local = {}
        local.update(__builtins__)
        local.update({
            '__name__'  : '__console__',
            '__doc__'   : None,
            'exit'      : self._python_exit,
            'self'      : self,
            'arg'       : arg,
            'winappdbg' : winappdbg,
        })
        try:
            code.interact(banner=banner, local=local)
        except SystemExit:
            # We need to catch it so it doesn't kill our program.
            pass 
Example #11
Source File: PupyCmd.py    From NoobSec-Toolkit with GNU General Public License v2.0 6 votes vote down vote up
def do_python(self,arg):
		""" start the local python interpreter (for debugging purposes) """
		orig_exit=builtins.exit
		orig_quit=builtins.quit
		def disabled_exit(*args, **kwargs):
			self.display_warning("exit() disabled ! use ctrl+D to exit the python shell")
		builtins.exit=disabled_exit
		builtins.quit=disabled_exit
		oldcompleter=readline.get_completer()
		try:
			local_ns={"pupsrv":self.pupsrv}
			readline.set_completer(PythonCompleter(local_ns=local_ns).complete)
			readline.parse_and_bind('tab: complete')
			code.interact(local=local_ns)
		except Exception as e:
			self.display_error(str(e))
		finally:
			readline.set_completer(oldcompleter)
			readline.parse_and_bind('tab: complete')
			builtins.exit=orig_exit
			builtins.quit=orig_quit 
Example #12
Source File: PupyCmd.py    From NoobSec-Toolkit with GNU General Public License v2.0 6 votes vote down vote up
def do_python(self,arg):
		""" start the local python interpreter (for debugging purposes) """
		orig_exit=builtins.exit
		orig_quit=builtins.quit
		def disabled_exit(*args, **kwargs):
			self.display_warning("exit() disabled ! use ctrl+D to exit the python shell")
		builtins.exit=disabled_exit
		builtins.quit=disabled_exit
		oldcompleter=readline.get_completer()
		try:
			local_ns={"pupsrv":self.pupsrv}
			readline.set_completer(PythonCompleter(local_ns=local_ns).complete)
			readline.parse_and_bind('tab: complete')
			code.interact(local=local_ns)
		except Exception as e:
			self.display_error(str(e))
		finally:
			readline.set_completer(oldcompleter)
			readline.parse_and_bind('tab: complete')
			builtins.exit=orig_exit
			builtins.quit=orig_quit 
Example #13
Source File: today_python_console.py    From pythonista-scripts with MIT License 6 votes vote down vote up
def main():
	kb = Keyboard()
	
	if appex.is_widget():
		appex.set_widget_view(kb.root)
	else:
		kb.root.present("sheet")
	
	def read(self, size=-1):
		return kb.read(size)
	
	def readline(self):
		return kb.read()
	
	sys.stdin.__class__.read = read
	sys.stdin.__class__.readline = readline
	
	code.interact() 
Example #14
Source File: client.py    From yolo with Apache License 2.0 6 votes vote down vote up
def shell(self, stage):
        self.set_up_yolofile_context(stage=stage)
        self._yolo_file = self.yolo_file.render(**self.context)

        # Set up AWS credentials for the shell
        self._setup_aws_credentials_in_environment(
            self.context.account.account_number,
            self.context.stage.region,
        )

        # Select Python shell
        if have_bpython:
            bpython.embed()
        elif have_ipython:
            start_ipython(argv=[])
        else:
            code.interact() 
Example #15
Source File: app.py    From kibitzr with MIT License 6 votes vote down vote up
def check_forever(self, checkers):
        timeline.schedule_checks(checkers)
        logger.info("Starting infinite loop")
        while not self.signals['reload_conf_pending']:
            if self.signals['interrupted']:
                break
            if self.signals['open_backdoor']:
                self.signals['open_backdoor'] = False
                code.interact(
                    banner="Kibitzr debug shell",
                    local=locals(),
                )
            timeline.run_pending()
            if self.signals['interrupted']:
                break
            time.sleep(1) 
Example #16
Source File: cci.py    From CumulusCI with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def shell(runtime, script=None, python=None):
    # alias for backwards-compatibility
    variables = {
        "config": runtime,
        "runtime": runtime,
        "project_config": runtime.project_config,
    }

    if script:
        if python:
            raise click.UsageError("Cannot specify both --script and --python")
        runpy.run_path(script, init_globals=variables)
    elif python:
        exec(python, variables)
    else:
        code.interact(local=variables) 
Example #17
Source File: cli.py    From quart with MIT License 5 votes vote down vote up
def shell_command(info: ScriptInfo) -> None:
    app = info.load_app()
    context = {}
    context.update(app.make_shell_context())

    banner = f"Python {sys.version} on {sys.platform} running {app.import_name}"
    code.interact(banner=banner, local=context) 
Example #18
Source File: console.py    From yatsm with MIT License 5 votes vote down vote up
def open_interpreter(model, message=None, variables=None, funcs=None):
    """ Opens an (I)Python interpreter

    Args:
        model (YATSM model): Pass YATSM model to work with
        message (str, optional): Additional message to pass to user in banner
        variables (dict of objects, optional): Variables available in (I)Python
            session
        funcs (dict of callable, optional): Functions available in (I)Python
            session

    """
    local = dict(_funcs, model=model, np=np, plt=plt)
    if variables:
        local.update(variables)
    if funcs:
        local.update(funcs)

    banner = """\
        YATSM {yver} Interactive Interpreter (Python {pver})
        Type "help(model)" for info on YATSM model methods.
        NumPy and matplotlib.pyplot are already imported as "np" and "plt".
    """.format(
        yver=__version__,
        pver='.'.join(map(str, sys.version_info[:3])),
        funcs='\n\t'.join([k for k in local])
    )
    banner = textwrap.dedent(banner)
    if isinstance(message, str):
        banner += '\n' + message

    try:
        import IPython
        IPython.InteractiveShell.banner1 = banner
        IPython.start_ipython(argv=[], user_ns=local)
    except:
        code.interact(banner, local=local) 
Example #19
Source File: cli.py    From recruit with Apache License 2.0 5 votes vote down vote up
def shell_command():
    """Runs an interactive Python shell in the context of a given
    Flask application.  The application will populate the default
    namespace of this shell according to it's configuration.

    This is useful for executing small snippets of management code
    without having to manually configure the application.
    """
    import code
    from flask.globals import _app_ctx_stack
    app = _app_ctx_stack.top.app
    banner = 'Python %s on %s\nApp: %s [%s]\nInstance: %s' % (
        sys.version,
        sys.platform,
        app.import_name,
        app.env,
        app.instance_path,
    )
    ctx = {}

    # Support the regular Python interpreter startup script if someone
    # is using it.
    startup = os.environ.get('PYTHONSTARTUP')
    if startup and os.path.isfile(startup):
        with open(startup, 'r') as f:
            eval(compile(f.read(), startup, 'exec'), ctx)

    ctx.update(app.make_shell_context())

    code.interact(banner=banner, local=ctx) 
Example #20
Source File: main.py    From Bowler with MIT License 5 votes vote down vote up
def do(interactive: bool, query: str, paths: List[str]) -> None:
    """Execute a query or enter interactive mode."""
    if not query or query == "-":

        namespace = {"Query": Query, "START": START, "SYMBOL": SYMBOL, "TOKEN": TOKEN}

        try:
            import IPython

            IPython.start_ipython(argv=[], user_ns=namespace)

        except ImportError:
            import code as _code

            _code.interact(local=namespace)

        finally:
            return

    code = compile(query, "<console>", "eval")
    result = eval(code)  # noqa eval() - developer tool, hopefully they're not dumb

    if isinstance(result, Query):
        if result.retcode:
            exc = click.ClickException("query failed")
            exc.exit_code = result.retcode
            raise exc
        result.diff(interactive=interactive)
    elif result:
        click.echo(repr(result)) 
Example #21
Source File: remote_api_shell.py    From browserscope with Apache License 2.0 5 votes vote down vote up
def remote_api_shell(servername, appid, path, secure, rpc_server_factory):
  """Actually run the remote_api_shell."""


  remote_api_stub.ConfigureRemoteApi(appid, path, auth_func,
                                     servername=servername,
                                     save_cookies=True, secure=secure,
                                     rpc_server_factory=rpc_server_factory)
  remote_api_stub.MaybeInvokeAuthentication()


  os.environ['SERVER_SOFTWARE'] = 'Development (remote_api_shell)/1.0'

  if not appid:

    appid = os.environ['APPLICATION_ID']
  sys.ps1 = '%s> ' % appid
  if readline is not None:

    readline.parse_and_bind('tab: complete')
    atexit.register(lambda: readline.write_history_file(HISTORY_PATH))
    if os.path.exists(HISTORY_PATH):
      readline.read_history_file(HISTORY_PATH)


  if '' not in sys.path:
    sys.path.insert(0, '')

  preimported_locals = {
      'memcache': memcache,
      'urlfetch': urlfetch,
      'users': users,
      'db': db,
      'ndb': ndb,
      }


  code.interact(banner=BANNER, local=preimported_locals) 
Example #22
Source File: cli.py    From jbox with MIT License 5 votes vote down vote up
def shell_command():
    """Runs an interactive Python shell in the context of a given
    Flask application.  The application will populate the default
    namespace of this shell according to it's configuration.

    This is useful for executing small snippets of management code
    without having to manually configuring the application.
    """
    import code
    from flask.globals import _app_ctx_stack
    app = _app_ctx_stack.top.app
    banner = 'Python %s on %s\nApp: %s%s\nInstance: %s' % (
        sys.version,
        sys.platform,
        app.import_name,
        app.debug and ' [debug]' or '',
        app.instance_path,
    )
    ctx = {}

    # Support the regular Python interpreter startup script if someone
    # is using it.
    startup = os.environ.get('PYTHONSTARTUP')
    if startup and os.path.isfile(startup):
        with open(startup, 'r') as f:
            eval(compile(f.read(), startup, 'exec'), ctx)

    ctx.update(app.make_shell_context())

    code.interact(banner=banner, local=ctx) 
Example #23
Source File: commands.py    From jbox with MIT License 5 votes vote down vote up
def run(self, no_ipython, no_bpython):
        """
        Runs the shell.  If no_bpython is False or use_bpython is True, then
        a BPython shell is run (if installed).  Else, if no_ipython is False or
        use_python is True then a IPython shell is run (if installed).
        """

        context = self.get_context()

        if not no_bpython:
            # Try BPython
            try:
                from bpython import embed
                embed(banner=self.banner, locals_=context)
                return
            except ImportError:
                pass

        if not no_ipython:
            # Try IPython
            try:
                try:
                    # 0.10.x
                    from IPython.Shell import IPShellEmbed
                    ipshell = IPShellEmbed(banner=self.banner)
                    ipshell(global_ns=dict(), local_ns=context)
                except ImportError:
                    # 0.12+
                    from IPython import embed
                    embed(banner1=self.banner, user_ns=context)
                return
            except ImportError:
                pass

        # Use basic python shell
        code.interact(self.banner, local=context) 
Example #24
Source File: cmds.py    From sea with MIT License 5 votes vote down vote up
def console():
    banner = """
        [Sea Console]:
        the following vars are included:
        `app` (the current app)
        """
    ctx = {'app': current_app}
    try:
        from IPython import embed
        h, kwargs = embed, dict(banner1=banner, user_ns=ctx, colors="neutral")
    except ImportError:
        import code
        h, kwargs = code.interact, dict(banner=banner, local=ctx)
    h(**kwargs)
    return 0 
Example #25
Source File: shell.py    From GTDWeb with GNU General Public License v2.0 5 votes vote down vote up
def handle(self, **options):
        try:
            if options['plain']:
                # Don't bother loading IPython, because the user wants plain Python.
                raise ImportError

            self.run_shell(shell=options['interface'])
        except ImportError:
            import code
            # Set up a dictionary to serve as the environment for the shell, so
            # that tab completion works on objects that are imported at runtime.
            # See ticket 5082.
            imported_objects = {}
            try:  # Try activating rlcompleter, because it's handy.
                import readline
            except ImportError:
                pass
            else:
                # We don't have to wrap the following import in a 'try', because
                # we already know 'readline' was imported successfully.
                import rlcompleter
                readline.set_completer(rlcompleter.Completer(imported_objects).complete)
                readline.parse_and_bind("tab:complete")

            # We want to honor both $PYTHONSTARTUP and .pythonrc.py, so follow system
            # conventions and get $PYTHONSTARTUP first then .pythonrc.py.
            if not options['no_startup']:
                for pythonrc in (os.environ.get("PYTHONSTARTUP"), '~/.pythonrc.py'):
                    if not pythonrc:
                        continue
                    pythonrc = os.path.expanduser(pythonrc)
                    if not os.path.isfile(pythonrc):
                        continue
                    try:
                        with open(pythonrc) as handle:
                            exec(compile(handle.read(), pythonrc, 'exec'), imported_objects)
                    except NameError:
                        pass
            code.interact(local=imported_objects) 
Example #26
Source File: pdbpp.py    From pdbpp with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def do_interact(self, arg):
        """
        interact

        Start an interative interpreter whose global namespace
        contains all the names found in the current scope.
        """
        ns = self.curframe.f_globals.copy()
        ns.update(self.curframe_locals)
        code.interact("*interactive*", local=ns) 
Example #27
Source File: console.py    From plasma with GNU General Public License v3.0 5 votes vote down vote up
def __exec_py(self, args):
        ns = {"api": self.api, "args": args[1:], "analyzer": self.analyzer}
        ns.update(EXPORTED_SYMBOLS)
        if len(args) > 1:
            if args[1].startswith("!"):
                args[1] = "%s/%s" % (PLASMA_SCRIPTS_DIR, args[1][1:])
            exec(open(args[1]).read(), ns)
        else:
            readline.set_completer(rlcompleter.Completer(ns).complete)
            code.interact(local=ns)
            readline.set_completer(self.comp.complete) 
Example #28
Source File: simple_console.py    From lambda-packs with MIT License 5 votes vote down vote up
def main(_):
  """Run an interactive console."""
  code.interact()
  return 0 
Example #29
Source File: simple_console.py    From auto-alt-text-lambda-api with MIT License 5 votes vote down vote up
def main(_):
  """Run an interactive console."""
  code.interact()
  return 0 
Example #30
Source File: interact.py    From sndlatr with Apache License 2.0 5 votes vote down vote up
def main():
    opts = command_line()
    print('Connecting...')
    client = create_client_from_config(opts)
    print('Connected.')
    banner = '\nIMAPClient instance is "c"'

    def ipython_011(c):
        from IPython.frontend.terminal.embed import InteractiveShellEmbed
        ipshell = InteractiveShellEmbed(banner1=banner)
        ipshell('')

    def ipython_010(c):
        from IPython.Shell import IPShellEmbed
        IPShellEmbed('', banner=banner)()

    def builtin(c):
        import code
        code.interact(banner, local=dict(c=c))
    
    for shell_attempt in (ipython_011, ipython_010, builtin):
        try:
            shell_attempt(client)
            break
        except ImportError:
            pass