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 9 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: 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 #4
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 #5
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 #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: 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 #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: 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 #11
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 #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: 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 #14
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 #15
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 #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: interactive.py    From packet-queue with Apache License 2.0 5 votes vote down vote up
def main():
  params, pipes, _ = command.configure()

  def run_shell():
    shell_vars = {
        'p': ParamsProxy(params),
        'm': MeterProxy(pipes),
    }
    code.interact(banner=BANNER, local=shell_vars)

  deferred = threads.deferToThread(run_shell)
  deferred.addCallback(lambda result: reactor.stop())
  reactor.run() 
Example #18
Source File: classic.py    From NoobSec-Toolkit with GNU General Public License v2.0 5 votes vote down vote up
def interact(conn, namespace = None):
    """remote interactive interpreter
    
    :param conn: the RPyC connection
    :param namespace: the namespace to use (a ``dict``)
    """
    if namespace is None:
        namespace = {}
    namespace["conn"] = conn
    with redirected_stdio(conn):
        conn.execute("""def _rinteract(ns):
            import code
            code.interact(local = dict(ns))""")
        conn.namespace["_rinteract"](namespace) 
Example #19
Source File: shell.py    From datastore-ndb-python with Apache License 2.0 5 votes vote down vote up
def shell():

  if (not os.environ.get('DATASTORE_APP_ID', None)
      and not os.environ.get('DATASTORE_PROJECT_ID', None)):
    raise ValueError('Must set either DATASTORE_APP_ID or DATASTORE_PROJECT_ID'
                     ' environment variable.')

  ndb.get_context().set_memcache_policy(False)
  ndb.get_context().set_cache_policy(False)

  # ndb will set the application ID.
  application_id = os.environ['APPLICATION_ID']
  id_resolver = datastore_pbs.IdResolver((application_id,))
  project_id = id_resolver.resolve_project_id(application_id)

  banner = """ndb shell
  Python %s
  Project: %s
  The ndb module is already imported.
  """ % (sys.version, project_id)

  imports = {
    'ndb': ndb,
  }

  # set up the environment
  os.environ['SERVER_SOFTWARE'] = 'Development (ndb_shell)/0.1'

  sys.ps1 = '%s> ' % project_id
  if readline is not None:
    # set up readline
    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)

  code.interact(banner=banner, local=imports) 
Example #20
Source File: shell.py    From pysmt with Apache License 2.0 5 votes vote down vote up
def interactive(self):
        # Enable infix notation in Interactive mode
        get_env().enable_infix_notation = True
        try:
            import IPython
            print(welcome_msg)
            IPython.embed()
        except ImportError:
            import code
            code.interact(welcome_msg) 
Example #21
Source File: __main__.py    From alpaca-trade-api-python with Apache License 2.0 5 votes vote down vote up
def run(args):
    api = REST(**args)
    try:
        from IPython import embed
        embed()
    except ImportError:
        import code
        code.interact(locals=locals()) 
Example #22
Source File: pdb.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
def do_interact(self, arg):
        """interact

        Start an interactive interpreter whose global namespace
        contains all the (global and local) names found in the current scope.
        """
        ns = self.curframe.f_globals.copy()
        ns.update(self.curframe_locals)
        code.interact("*interactive*", local=ns) 
Example #23
Source File: __init__.py    From api with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def shell():
    """Run a Python shell in the app context."""

    try:
        import IPython
    except ImportError:
        IPython = None

    if IPython is not None:
        IPython.embed(banner1="", user_ns=current_app.make_shell_context())
    else:
        import code

        code.interact(banner="", local=current_app.make_shell_context()) 
Example #24
Source File: shell.py    From singularity-cli with Mozilla Public License 2.0 5 votes vote down vote up
def python(image):
    """give the user a python shell
    """
    import code

    client = prepare_client(image)
    code.interact(local={"client": client}) 
Example #25
Source File: simple_console.py    From deep_image_model with Apache License 2.0 5 votes vote down vote up
def main(_):
  """Run an interactive console."""
  code.interact()
  return 0 
Example #26
Source File: simple_console_for_windows.py    From deep_image_model with Apache License 2.0 5 votes vote down vote up
def main(_):
  """Run an interactive console."""
  code.interact()
  return 0 
Example #27
Source File: simple_console.py    From deep_image_model with Apache License 2.0 5 votes vote down vote up
def main(_):
  """Run an interactive console."""
  code.interact()
  return 0 
Example #28
Source File: python.py    From contrail-api-cli with MIT License 5 votes vote down vote up
def __call__(self):
        try:
            from ptpython.repl import embed
            embed(globals(), None)
        except ImportError:
            try:
                from IPython import embed
                embed()
            except ImportError:
                import code
                code.interact(banner="Launching standard python repl", readfunc=None, local=globals()) 
Example #29
Source File: pdb.py    From ironpython3 with Apache License 2.0 5 votes vote down vote up
def do_interact(self, arg):
        """interact

        Start an interactive interpreter whose global namespace
        contains all the (global and local) names found in the current scope.
        """
        ns = self.curframe.f_globals.copy()
        ns.update(self.curframe_locals)
        code.interact("*interactive*", local=ns) 
Example #30
Source File: console.py    From learn_python3_spider with MIT License 5 votes vote down vote up
def start_python_console(namespace=None, banner='', shells=None):
    """Start Python console bound to the given namespace.
    Readline support and tab completion will be used on Unix, if available.
    """
    if namespace is None:
        namespace = {}

    try:
        shell = get_shell_embed_func(shells)
        if shell is not None:
            shell(namespace=namespace, banner=banner)
    except SystemExit: # raised when using exit() in python code.interact
        pass