def interact(self): """Starts an InteractiveConsole.""" sys.stdout = sys.__stdout__ console = InteractiveConsole(locals=self.frame) console.interact('# Interactive console.' ' Type exit() to quit') sys.stdout = logger
def pudb_shell(_globals, _locals): """ This example shell runs a classic Python shell. It is based on run_classic_shell in pudb.shell. """ # Many shells only let you pass in a single locals dictionary, rather than # separate globals and locals dictionaries. In this case, you can use # pudb.shell.SetPropagatingDict to automatically merge the two into a # single dictionary. It does this in such a way that assignments propogate # to _locals, so that when the debugger is at the module level, variables # can be reassigned in the shell. from pudb.shell import SetPropagatingDict ns = SetPropagatingDict([_locals, _globals], _locals) try: import readline import rlcompleter HAVE_READLINE = True except ImportError: HAVE_READLINE = False if HAVE_READLINE: readline.set_completer( rlcompleter.Completer(ns).complete) readline.parse_and_bind("tab: complete") readline.clear_history() from code import InteractiveConsole cons = InteractiveConsole(ns) cons.interact("Press Ctrl-D to return to the debugger")
def interact(self): old_raw_input = __builtin__.raw_input old_displayhook = sys.displayhook old_excepthook = sys.excepthook old_stdin = sys.stdin old_stdout = sys.stdout old_stderr = sys.stderr old_help = __builtin__.help old_quit = __builtin__.quit __builtin__.raw_input = self.raw_input __builtin__.help = "Close window to exit." __builtin__.quit = "Close window to exit." sys.displayhook = self.displayhook sys.excepthook = self.excepthook sys.stdin = self.pipe.stdin sys.stdout = self.pipe.stdout sys.stderr = self.pipe.stderr try: self.pipe.expect('RemoteConsole.initialize', repr(sys.version_info), sys.executable, os.getpid()) InteractiveConsole.interact(self) finally: __builtin__.raw_input = old_raw_input __builtin__.help = old_help __builtin__.quit = old_quit sys.displayhook = old_displayhook sys.excepthook = old_excepthook sys.stdin = old_stdin sys.stdout = old_stdout sys.stderr = old_stderr
def do_py(self, arg): """ :: Usage: py py COMMAND Arguments: COMMAND the command to be executed Description: The command without a parameter will be executed and the interactive python mode is entered. The python mode can be ended with ``Ctrl-D`` (Unix) / ``Ctrl-Z`` (Windows), ``quit()``,'`exit()``. Non-python commands can be issued with ``cmd("your command")``. If the python code is located in an external file it can be run with ``run("filename.py")``. In case a COMMAND is provided it will be executed and the python interpreter will return to the command shell. This code is copied from Cmd2. """ self.pystate['self'] = self arg = arg.strip() localvars = (self.locals_in_py and self.pystate) or {} interp = InteractiveConsole(locals=localvars) interp.runcode('import sys, os;sys.path.insert(0, os.getcwd())') if arg: interp.runcode(arg) else: def quit(): raise EmbeddedConsoleExit def onecmd(arg): return self.onecmd(arg + '\n') def run(arg): try: f = open(arg) interp.runcode(f.read()) f.close() except IOError as e: self.perror(e) self.pystate['quit'] = quit self.pystate['exit'] = quit self.pystate['cmd'] = onecmd self.pystate['run'] = run try: cprt = 'Type "help", "copyright", "credits" or "license" for more information.' keepstate = Statekeeper(sys, ('stdin', 'stdout')) sys.stdout = self.stdout sys.stdin = self.stdin interp.interact(banner="Python %s on %s\n%s\n(%s)\n%s" % (sys.version, sys.platform, cprt, self.__class__.__name__, self.do_py.__doc__)) except EmbeddedConsoleExit: pass keepstate.restore()
def _embed_vanilla(): """ Embed vanilla python interpreter (two frames back). This function is adapted from a StackOverflow answer by user "Havok", which you can find here: <http://stackoverflow.com/a/28423594>. """ from code import InteractiveConsole from inspect import currentframe caller = currentframe().f_back.f_back env = {} env.update(caller.f_globals) env.update(caller.f_locals) try: import readline import rlcompleter readline.set_completer(rlcompleter.Completer(env).complete) readline.parse_and_bind("tab: complete") except ImportError: pass shell = InteractiveConsole(env) shell.interact( _embed_banner.format( filename=caller.f_code.co_filename, line=caller.f_lineno ) ) return True
def interact(self): try: InteractiveConsole.interact( self, banner=(f"Electron Cash {version.PACKAGE_VERSION}\n" f"Type 'help' for available commands and variables.")) except SystemExit: pass
def repl(): trig.run() while True: try: phrase = input(PROMPT) if len(phrase) == 0: continue command_parser(phrase) except ( TypeError, KeyError, ValueError, IndexError, SyntaxError, NameError, ) as e: print("Error due to malformed input: %s Please try again." % e) except (EOFError, KeyboardInterrupt): banner = ''' Debugging shell called with keyboard interrupt. You can get back by hitting CTRL-D To quit, write "quit()"''' from code import InteractiveConsole import readline import rlcompleter context = globals().copy() context.update(locals()) readline.set_completer(rlcompleter.Completer(context).complete) readline.parse_and_bind("tab: complete") ic = InteractiveConsole(context) try: ic.interact(banner) except (EOFError): pass
def interactive_client(file, host, port, cache_size, readonly, repair, startup): if file: storage = FileStorage(file, readonly=readonly, repair=repair) description = file else: wait_for_server(host, port) storage = ClientStorage(host=host, port=port) description = "%s:%s" % (host, port) connection = Connection(storage, cache_size=cache_size) namespace = {'connection': connection, 'root': connection.get(0), 'get': connection.get, 'sys': sys, 'os': os, 'p64': p64, 'u64': u64, 'pp': pprint} configure_readline(namespace, os.path.expanduser("~/.durushistory")) console = InteractiveConsole(namespace) if startup: console.runsource('execfile("%s")' % os.path.expanduser(startup)) help = (' connection -> the connection\n' ' root -> get(0)\n' ' get(oid) -> get an object\n' ' pp(object) -> pretty-print') console.interact('Durus (%s)\n%s' % (description, help))
def shell(*args): """Interactive Shell""" if "--ipython" in args: """IPython Interactive Shell - IPython must be installed to use.""" # remove an argument that confuses ipython sys.argv.pop(sys.argv.index("--ipython")) from IPython.Shell import IPShellEmbed import infogami # noqa: F401 from infogami.utils import delegate from infogami.core import db # noqa: F401 from infogami.utils.context import context as ctx # noqa: F401 delegate.fakeload() ipshell = IPShellEmbed() ipshell() else: from code import InteractiveConsole console = InteractiveConsole() console.push("import infogami") console.push("from infogami.utils import delegate") console.push("from infogami.core import db") console.push("from infogami.utils.context import context as ctx") console.push("delegate.fakeload()") console.interact()
def __main__(path=".", script=None, **flags): if not script: import os if os.path.isfile(path): path, script = ".", path env = dict(__utils) if flags.get('log',False): store = LogicalLogStore(path) env['logs'] = store else: store = GraphDatabaseStore(path) env['store'] = store if script: with open(script) as script: store.initialize() try: exec(script.read(), env) finally: store.shutdown() else: from code import InteractiveConsole console = InteractiveConsole(locals=env) store.initialize() try: console.interact( banner="Neo4j Store introspection console (Python)") finally: store.shutdown()
def main(): ''' The main entry point ''' salt_vars = get_salt_vars() def salt_outputter(value): ''' Use Salt's outputters to print values to the shell ''' if value is not None: try: import __builtin__ __builtin__._ = value except ImportError: __builtins__._ = value salt.output.display_output(value, '', salt_vars['__opts__']) sys.displayhook = salt_outputter # Set maximum number of items that will be written to the history file readline.set_history_length(300) if os.path.exists(HISTFILE): readline.read_history_file(HISTFILE) atexit.register(savehist) atexit.register(lambda: sys.stdout.write('Salt you later!\n')) saltrepl = InteractiveConsole(locals=salt_vars) saltrepl.interact(banner=__doc__)
def handle(self, conn, address): f = getcurrent()._fileobj = _fileobject(conn) f.stderr = self.stderr getcurrent().switch_in() try: console = InteractiveConsole(self.locals) # __builtins__ may either be the __builtin__ module or # __builtin__.__dict__ in the latter case typing # locals() at the backdoor prompt spews out lots of # useless stuff try: import __builtin__ console.locals["__builtins__"] = __builtin__ except ImportError: import builtins console.locals["builtins"] = builtins console.interact(banner=self.banner) except SystemExit: # raised by quit() if not PY3: sys.exc_clear() finally: conn.close() f.close() if PYPY: # The underlying socket somewhere has a reference # that's not getting closed until finalizers run. # Without running them, test__backdoor.Test.test_sys_exit # hangs forever gc.collect()
class ClassicPythonShell(Shell, ConsoleProgressBarMixin): """Classic Python shell interface. This class allows igraph to be embedded in Python's shell.""" def __init__(self): """Constructor. Imports Python's classic shell""" Shell.__init__(self) self._shell = None try: self.__class__.progress_bar = ProgressBar(TerminalController()) except ValueError: # Terminal is not capable enough, disable progress handler del self.__class__._progress_handler def __call__(self): """Starts the embedded shell.""" if self._shell is None: from code import InteractiveConsole self._shell = InteractiveConsole() print >> sys.stderr, "igraph %s running inside " % __version__, self._shell.runsource("from igraph import *") self._shell.interact()
def pudb_shell(_globals, _locals): """ This example shell runs a classic Python shell. It is based on run_classic_shell in pudb.shell. """ # Many shells only let you pass in a single locals dictionary, rather than # separate globals and locals dictionaries. In this case, you can use # pudb.shell.SetPropagatingDict to automatically merge the two into a # single dictionary. It does this in such a way that assignments propogate # to _locals, so that when the debugger is at the module level, variables # can be reassigned in the shell. from pudb.shell import SetPropagatingDict ns = SetPropagatingDict([_locals, _globals], _locals) try: import readline import rlcompleter HAVE_READLINE = True except ImportError: HAVE_READLINE = False if HAVE_READLINE: readline.set_completer(rlcompleter.Completer(ns).complete) readline.parse_and_bind("tab: complete") readline.clear_history() from code import InteractiveConsole cons = InteractiveConsole(ns) cons.interact("Press Ctrl-D to return to the debugger")
def loop(editor): try: editor.stop_async_io() global name_space if name_space is None: print('\tuse :eval in a python source file to use its name_space.') name_space = {} else: print() print('\tBuffer correctly evaluated.') print() console = Console(locals=name_space) #, editor=editor) try: with local_completer: readline.set_completer(Completer(name_space).complete) console.interact() except SystemExit: pass name_space = None #console.save_history() return 'normal' finally: editor.start_async_io()
def run(self): try: console = InteractiveConsole(self.locals) console.interact() finally: self.switch_out() self.finalize()
def __main__(path=".", script=None, **flags): if not script: import os if os.path.isfile(path): path, script = ".", path env = dict(__utils) if flags.get('log', False): store = LogicalLogStore(path) env['logs'] = store else: store = GraphDatabaseStore(path) env['store'] = store if script: with open(script) as script: store.initialize() try: exec(script.read(), env) finally: store.shutdown() else: from code import InteractiveConsole console = InteractiveConsole(locals=env) store.initialize() try: console.interact( banner="Neo4j Store introspection console (Python)") finally: store.shutdown()
def handle(self, args): context = globals().copy() context.update(locals()) readline.set_completer(rlcompleter.Completer(context).complete) readline.parse_and_bind('tab: complete') shell = InteractiveConsole(context) shell.interact()
def _run(self): try: console = InteractiveConsole(self.locals) console.interact() finally: self.switch_out() self.finalize()
def do_py(self, arg): """ :: Usage: py py COMMAND Arguments: COMMAND the command to be executed Description: The command without a parameter will be executed and the interactive python mode is entered. The python mode can be ended with ``Ctrl-D`` (Unix) / ``Ctrl-Z`` (Windows), ``quit()``,'`exit()``. Non-python commands can be issued with ``cmd("your command")``. If the python code is located in an external file it can be run with ``run("filename.py")``. In case a COMMAND is provided it will be executed and the python interpreter will return to the command shell. This code is copied from Cmd2. """ self.pystate['self'] = self arg = arg.strip() localvars = (self.locals_in_py and self.pystate) or {} interp = InteractiveConsole(locals=localvars) interp.runcode('import sys, os;sys.path.insert(0, os.getcwd())') if arg: interp.runcode(arg) else: def quit(): raise EmbeddedConsoleExit def onecmd(arg): return self.onecmd(arg + '\n') def run(arg): try: f = open(arg) interp.runcode(f.read()) f.close() except IOError, e: self.perror(e) self.pystate['quit'] = quit self.pystate['exit'] = quit self.pystate['cmd'] = onecmd self.pystate['run'] = run try: cprt = 'Type "help", "copyright", "credits" or "license" for more information.' keepstate = Statekeeper(sys, ('stdin', 'stdout')) sys.stdout = self.stdout sys.stdin = self.stdin interp.interact(banner="Python %s on %s\n%s\n(%s)\n%s" % (sys.version, sys.platform, cprt, self.__class__.__name__, self.do_py.__doc__)) except EmbeddedConsoleExit: pass keepstate.restore()
def run_classic_shell(locals, globals, first_time): if first_time: banner = "Hit Ctrl-D to return to PuDB." else: banner = "" ns = SetPropagatingDict([locals, globals], locals) from pudb.settings import get_save_config_path from os.path import join hist_file = join( get_save_config_path(), "shell-history") if HAVE_READLINE: readline.set_completer( rlcompleter.Completer(ns).complete) readline.parse_and_bind("tab: complete") try: readline.read_history_file(hist_file) except IOError: pass from code import InteractiveConsole cons = InteractiveConsole(ns) cons.interact(banner) if HAVE_READLINE: readline.write_history_file(hist_file)
def interactive_client(file, address, cache_size, readonly, repair, startup): if file: storage = FileStorage(file, readonly=readonly, repair=repair) description = file else: socket_address = SocketAddress.new(address) wait_for_server(address=socket_address) storage = ClientStorage(address=socket_address) description = socket_address connection = Connection(storage, cache_size=cache_size) console_module = ModuleType('__console__') sys.modules['__console__'] = console_module namespace = {'connection': connection, 'root': connection.get_root(), 'get': connection.get, 'sys': sys, 'os': os, 'int8_to_str': int8_to_str, 'str_to_int8': str_to_int8, 'pp': pprint} vars(console_module).update(namespace) configure_readline( vars(console_module), os.path.expanduser("~/.durushistory")) console = InteractiveConsole(vars(console_module)) if startup: src = '''with open('{fn}', 'rb') as _: _ = compile(_.read(), '{fn}', 'exec') exec(globals().pop('_')) '''.format(fn = os.path.expanduser(startup)).rstrip() console.runsource(src, '-stub-', 'exec') help = (' connection -> the Connection\n' ' root -> the root instance') console.interact('Durus %s\n%s' % (description, help))
def handle(self, conn, _address): # pylint: disable=method-hidden """ Interact with one remote user. .. versionchanged:: 1.1b2 Each connection gets its own ``locals`` dictionary. Previously they were shared in a potentially unsafe manner. """ fobj = conn.makefile(mode="rw") fobj = _fileobject(conn, fobj, self.stderr) getcurrent()._fileobj = fobj getcurrent().switch_in() try: console = InteractiveConsole(self._create_interactive_locals()) if sys.version_info[:3] >= (3, 6, 0): # Beginning in 3.6, the console likes to print "now exiting <class>" # but probably our socket is already closed, so this just causes problems. console.interact(banner=self.banner, exitmsg='') # pylint:disable=unexpected-keyword-arg else: console.interact(banner=self.banner) except SystemExit: # raised by quit() if hasattr(sys, 'exc_clear'): # py2 sys.exc_clear() finally: conn.close() fobj.close()
def handle(self, conn, _address): # pylint: disable=method-hidden """ Interact with one remote user. .. versionchanged:: 1.1b2 Each connection gets its own ``locals`` dictionary. Previously they were shared in a potentially unsafe manner. """ conn.setsockopt(socket.SOL_TCP, socket.TCP_NODELAY, True) # pylint:disable=no-member raw_file = conn.makefile(mode="r") getcurrent().stdin = _StdIn(conn, raw_file) getcurrent().stdout = _StdErr(conn, raw_file) # Swizzle the inputs getcurrent().switch_in() try: console = InteractiveConsole(self._create_interactive_locals()) if PY36: # Beginning in 3.6, the console likes to print "now exiting <class>" # but probably our socket is already closed, so this just causes problems. console.interact(banner=self.banner, exitmsg='') # pylint:disable=unexpected-keyword-arg else: console.interact(banner=self.banner) except SystemExit: # raised by quit(); obviously this cannot propagate. exc_clear() # Python 2 finally: raw_file.close() conn.close()
def interactive_client(file, address, cache_size, readonly, repair, startup, storage_class=None): if file: storage = get_storage(file, storage_class=storage_class, readonly=readonly, repair=repair) description = file else: socket_address = SocketAddress.new(address) wait_for_server(address=socket_address) storage = ClientStorage(address=socket_address) description = socket_address connection = Connection(storage, cache_size=cache_size) console_module = ModuleType('__console__') sys.modules['__console__'] = console_module namespace = {'connection': connection, 'root': connection.get_root(), 'get': connection.get, 'sys': sys, 'os': os, 'int8_to_str': int8_to_str, 'str_to_int8': str_to_int8, 'pp': pprint} vars(console_module).update(namespace) configure_readline( vars(console_module), os.path.expanduser("~/.durushistory")) console = InteractiveConsole(vars(console_module)) if startup: console.runsource('execfile("%s")' % os.path.expanduser(startup)) help = (' connection -> the Connection\n' ' root -> the root instance') console.interact('Durus %s\n%s' % (description, help))
def main(): ''' The main entry point ''' salt_vars = get_salt_vars() def salt_outputter(value): ''' Use Salt's outputters to print values to the shell ''' if value is not None: builtins._ = value salt.output.display_output(value, '', salt_vars['__opts__']) sys.displayhook = salt_outputter # Set maximum number of items that will be written to the history file readline.set_history_length(300) if os.path.exists(HISTFILE): readline.read_history_file(HISTFILE) atexit.register(savehist) atexit.register(lambda: sys.stdout.write('Salt you later!\n')) saltrepl = InteractiveConsole(locals=salt_vars) saltrepl.interact(banner=__doc__)
def handle(self, conn, address): file_obj = conn.makefile(mode='rw') file_obj = gevent.backdoor._fileobject(conn, file_obj, self.stderr) getcurrent()._fileobj = file_obj getcurrent().switch_in() file_obj.write('Password: '******'\r\n') salted = password + self.salt hash_digest = hashlib.sha256(salted).hexdigest() if not hash_digest == self.hash: file_obj.write('\nWrong password.\n') conn.close() file_obj.close() return try: console = InteractiveConsole(self._create_interactive_locals()) if sys.version_info[:3] >= (3, 6, 0): console.interact(banner=self.banner, exitmsg='') else: console.interact(banner=self.banner) except SystemExit: if hasattr(sys, 'exc_clear'): sys.exc_clear() finally: conn.close() file_obj.close()
def liveInspect(locals): if not isinstance(locals, dict): locals = {"t": locals} ic = InteractiveConsole(locals) try: ic.interact("Welcome to the live inspect console! press ctrl+D to resume the game\n your locals are {0}".format(locals)) except SystemExit, e: return #exit()
def interactive(localvars=None): """Interactive interpreter for debugging.""" if localvars == None: # extract locals from the calling frame - taken from IPython localvars = sys._getframe(0).f_back.f_locals from code import InteractiveConsole con = InteractiveConsole(localvars) con.interact()
def interact(self, banner=None): try: InteractiveConsole.interact(self, banner) except KeyboardInterrupt: if self.inQuery: self.inQuery = False self.buffer = [] print "Enter quit() or Ctrl-D to exit"
def run(self): try: vars = globals().copy() vars.update(locals()) console = InteractiveConsole(vars) console.interact() finally: self.switchOut() self.finalize()
def python(self): "Drops into a Python REPL" from code import InteractiveConsole console = InteractiveConsole(locals={"SESSION": self}) console.push("from leibniz import *") console.interact( ("Welcome. You're in an interactive python shell. Feel free to poke around " "in your current Leibniz session, which is available under the name SESSION."), "Dropping you back into Leibniz session.")
def interact(self, *args, **kwargs): sys.ps1 = self.ps1 puts(self.banner) try: import readline except ImportError: pass InteractiveConsole.interact(self, *args, **kwargs)
def run_console(): global console sys.stdin = FileObject(sys.stdin) console = InteractiveConsole({ 'client': client, 'player': Player(client.pipdata), 'inv': Inventory(client.pipdata), }) console.interact()
def run(self): try: console = InteractiveConsole(self.locals) console.interact() except BaseException as e: self.lastexception = sys.exc_info() finally: self.switch_out() self.finalize()
def shell(): """Interactive Shell""" from code import InteractiveConsole console = InteractiveConsole() console.push("import infogami") console.push("from infogami.utils import delegate") console.push("from infogami.core import db") console.push("from infogami.utils.context import context as ctx") console.push("delegate.fakeload()") console.interact()
def execute(self): """Execute the link.""" # this function calls the python session # in this session ds, settings, and process_manager are available from code import InteractiveConsole cons = InteractiveConsole(locals()) cons.interact( "\nStarting interactive session ... press Ctrl+d to exit.\n") return StatusCode.Success
def _run(self): try: try: console = InteractiveConsole(self.locals) console.interact() except SystemExit: # raised by quit() sys.exc_clear() finally: self.switch_out() self.finalize()
def interact(self): try: InteractiveConsole.interact( self, banner=( _("WARNING!") + "\n" + _("Do not enter code here that you don't understand. Executing the wrong " "code could lead to your coins being irreversibly lost.") + "\n" + "Type 'help' for available commands and variables.")) except SystemExit: pass
def main(): if len(sys.argv) > 1: f = sys.argv[1] code = open(f).read() lazy_exec(code) else: from code import InteractiveConsole console = InteractiveConsole(LazyEnv()) console.runcode("import readline") console.interact()
def interact(self, banner=None): if banner is None: banner = ( "Python {} on {}\n".format(sys.version, sys.platform) + "The current application context is available in the variable 'context'." ) try: InteractiveConsole.interact(self, banner) except SystemExit: pass
def eskapade_run(): """Run Eskapade. Top-level entry point for an Eskapade run started from the command line. Arguments specified by the user are parsed and converted to settings in the configuration object. Optionally, an interactive Python session is started when the run is finished. """ from escore import process_manager, ConfigObject, DataStore from escore.core import execution from escore.core.run_utils import create_arg_parser # create parser for command-line arguments parser = create_arg_parser() user_args = parser.parse_args() # create config object for settings if not user_args.unpickle_config: # create new config settings = ConfigObject() else: # read previously persisted settings if pickled file is specified conf_path = user_args.config_files.pop(0) settings = ConfigObject.import_from_file(conf_path) del user_args.unpickle_config # set configuration macros settings.add_macros(user_args.config_files) # set user options settings.set_user_opts(user_args) try: # run Eskapade execution.eskapade_run(settings) except Exception as exc: logger.error('{exc}', exc=exc) raise # start interpreter if requested (--interactive on command line) if settings.get('interactive'): # set Pandas display options import pandas as pd pd.set_option('display.width', 120) pd.set_option('display.max_columns', 50) # make datastore and config available in interactive session ds = process_manager.service(DataStore) settings = process_manager.service(ConfigObject) # start interactive session from code import InteractiveConsole cons = InteractiveConsole(locals()) cons.interact( "\nContinuing interactive session ... press Ctrl+d to exit.\n")
def process_message(self, message): self.logger.info("processing %s" % (message)) self.message = message from pprint import pprint loc=dict(locals()) loc['message'] = self.message c = InteractiveConsole(locals=loc) c.interact("interactive intercept") for key in loc: if key != '__builtins__': exec "%s = loc[%r]" % (key, key)
def __call__(self, command, what): from code import InteractiveConsole console = InteractiveConsole(locals={ 'twitter' : twitter, 'username' : username, 'tracker' : tracker, 'updates' : updates, 'configuration' : configuration }) console.interact("(entering python console)\n") print("(console closed.)")
def process_message(self, message): self.logger.info("processing %s" % (message)) self.message = message from pprint import pprint loc = dict(locals()) loc['message'] = self.message c = InteractiveConsole(locals=loc) c.interact("interactive intercept") for key in loc: if key != '__builtins__': exec "%s = loc[%r]" % (key, key)
def run(self, nodes, args): banner = textwrap.dedent(self.banner_template).strip('\n').format( pyversion=sys.version_info, version=version ) locals_ = self.base_locals.copy() locals_.update({ 'nodes': nodes, 'args': args }) self.setup_readline(locals_) console = InteractiveConsole(locals_) console.interact(banner)
def startInteractiveShell(self): vars = globals() ai = self.ai self.rect1 = Rect(Point(0, 0), Point(100, 100)) self.rect2 = Rect(Point(50, 50), Point(150, 150)) rect1 = self.rect1 rect2 = self.rect2 vars.update(locals()) shell = InteractiveConsole(vars) shell.interact()
def interact(self, banner=None): old_ps1 = getattr(sys, 'ps1', '') old_ps2 = getattr(sys, 'ps2', '') sys.ps1 = self.prompt sys.ps2 = "" stdin, stdout, stderr = (sys.stdin, sys.stdout, sys.stderr) sys.stdin, sys.stdout, sys.stderr = (self.stdin, self.stderr, self.stderr) logger.debug(self.locals) InteractiveConsole.interact(self, banner=banner); sys.stdin, sys.stdout, sys.stderr = (stdin, stdout, stderr) sys.ps1 = old_ps1 sys.ps2 = old_ps2
def shell(): """ Enters an interactive shell with an app instance and dependency resolver. """ import readline from code import InteractiveConsole helpers = {"app": app, "resolver": app.injector.get_resolver()} readline.parse_and_bind("tab: complete") interpreter = InteractiveConsole(helpers) interpreter.interact(f"Instances in scope: {', '.join(helpers)}.", "")