def _start_ipython(self, overrides, banner): try: from IPython.frontend.terminal.embed import InteractiveShellEmbed ipshell = InteractiveShellEmbed(banner1=banner, user_ns=overrides) ipshell() except ImportError: print(_('ipython is not available, set use_ipython to no'))
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. """ api_version = get_ipython_api_version() 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]) if api_version == '0.10': ipshell = IPython.Shell.IPShellEmbed() ipshell(header = __header % dd, local_ns = loc, global_ns = glo) else: from IPython.config.loader import Config cfg = Config() cfg.InteractiveShellEmbed.local_ns = loc cfg.InteractiveShellEmbed.global_ns = glo IPython.embed(config=cfg, banner2 = __header % dd) if api_version == '0.11': from IPython.frontend.terminal.embed import InteractiveShellEmbed else: from IPython.terminal.embed import InteractiveShellEmbed ipshell = InteractiveShellEmbed(config=cfg) del ipshell
def interact(): cfg = Config() ipshell = InteractiveShellEmbed(config=cfg, banner1="Androlyze version %s" % androconf.ANDROGUARD_VERSION) init_print_colors() ipshell()
def get_shell(): """ Returns a callable object that opens an interactive IPython shell. This code is taken directly from the IPython documentation. http://ipython.org/ipython-doc/dev/interactive/reference.html#embedding-ipython To use it, create the embedded shell object my_new_shell = get_shell.get_shell() and then call it, whenever you want to have an interactive shell my_new_shell() Note that, within this shell, you can modify variables, but the changes will not be propagated to the calling environment. """ try: get_ipython except NameError: banner = exit_msg = '' else: banner = '*** Nested interpreter ***' exit_msg = '*** Back in main IPython ***' # First import the embed function from IPython.frontend.terminal.embed import InteractiveShellEmbed # Now create the IPython shell instance. Put ipshell() anywhere in your code # where you want it to open. return InteractiveShellEmbed(banner1=banner, exit_msg=exit_msg)
def _run_shell(handler, module=None): def _handler(shell, etype, evalue, traceback, tb_offset=None): print("Sorry, {0}".format(str(evalue))) return None try: from IPython.frontend.terminal.embed import InteractiveShellEmbed import quantities as q print("Welcome to Concert {0}".format(concert.__version__)) if module: print(module.__doc__) globals().update(_get_module_variables(module)) with handler.applicationbound(): shell = InteractiveShellEmbed(banner1='') exceptions = (UnitError, LimitError, ParameterError, ReadAccessError, WriteAccessError) shell.set_custom_exc(exceptions, _handler) shell() except ImportError as exception: msg = "You must install IPython to run the Concert shell: {0}" print(msg.format(exception))
def ipshell(): if _ip_shell is not None: return _ip_shell from IPython.config.loader import Config try: get_ipython except NameError: nested = 0 cfg = Config() prompt_config = cfg.PromptManager prompt_config.in_template = 'In <\\#>: ' prompt_config.in2_template = ' .\\D.: ' prompt_config.out_template = 'Out<\\#>: ' else: cfg = Config() nested = 1 from IPython.frontend.terminal.embed import InteractiveShellEmbed # Now create an instance of the embeddable shell. The first argument is a # string with options exactly as you would type them if you were starting # IPython at the system command line. Any parameters you want to define for # configuration can thus be specified here. ipshell = InteractiveShellEmbed( config=cfg, banner1='Dropping into IPython', exit_msg='Leaving Interpreter, back to program.') _ip_shell = ipshell return ipshell
def main(): loop = asyncio.get_event_loop() db = None async def before_start(loop, DB_CONFIG): db = await BaseConnection(loop=loop).init(DB_CONFIG=DB_CONFIG) return db db = loop.run_until_complete(before_start(loop, DB_CONFIG)) local_vars = locals() local_vars['db'] = db local_vars['loop'] = loop def fetch(sql): async def run(sql): async with db as cur: res = await cur.fetch(sql) return res res = loop.run_until_complete(run(sql)) return res local_vars['fetch'] = fetch try: from IPython.frontend.terminal.embed import InteractiveShellEmbed ipshell = InteractiveShellEmbed() ipshell() except ImportError: import code pyshell = code.InteractiveConsole(locals=local_vars) pyshell.interact()
def main(self): if self.input_file == sys.stdin: self.argparser.error('csvpy cannot accept input on STDIN (pipe).') # Attempt reading filename, will cause lazy loader to access file and raise error if it does not exist filename = self.input_file.name if self.args.as_dict: klass = agate.csv.DictReader class_name = 'agate.csv.DictReader' variable_name = 'reader' elif self.args.as_agate: klass = agate.Table.from_csv class_name = 'agate.Table' variable_name = 'table' else: klass = agate.csv.reader class_name = 'agate.csv.reader' variable_name = 'reader' variable = klass(self.input_file, **self.reader_kwargs) welcome_message = 'Welcome! "%s" has been loaded in an %s object named "%s".' % (filename, class_name, variable_name) try: from IPython.frontend.terminal.embed import InteractiveShellEmbed exec('%s = variable' % variable_name) ipy = InteractiveShellEmbed(banner1=welcome_message) ipy() except ImportError: import code code.interact(welcome_message, local={variable_name: variable})
def get_def_colors(): # Inspirated in https://github.com/gotcha/ipdb/blob/master/ipdb/__main__.py def_colors = 'Linux' import IPython if IPython.__version__ > '0.10.2': from IPython.core.debugger import Pdb try: get_ipython except NameError: from IPython.frontend.terminal.embed import InteractiveShellEmbed ipshell = InteractiveShellEmbed() def_colors = ipshell.colors else: try: def_colors = get_ipython.im_self.colors except AttributeError: def_colors = get_ipython.__self__.colors else: from IPython.Debugger import Pdb from IPython.Shell import IPShell from IPython import ipapi ip = ipapi.get() if ip is None: IPShell(argv=['']) ip = ipapi.get() def_colors = ip.options.colors return def_colors
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) 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.')
def debug(frame=None, frames_back=1): if IPython.__version__ >= '0.11': from IPython.core.debugger import Pdb try: ip = get_ipython() except NameError: from IPython.frontend.terminal.embed \ import InteractiveShellEmbed ip = InteractiveShellEmbed() colors = ip.colors else: from IPython.Debugger import Pdb from IPython.Shell import IPShell from IPython import ipapi ip = ipapi.get() if ip is None: IPShell(argv=['']) ip = ipapi.get() colors = ip.options.colors sys.excepthook = old_excepthook if frame is None: frame = sys._getframe(frames_back) Pdb(colors).set_trace(frame)
def setup_ipython_shell(shell_api=None): ipy_config = _setup_ipython_config() # monkeypatch the ipython inputhook to be gevent-friendly import gevent # should be auto-monkey-patched by pyon already. import select import sys import os def stdin_ready(): infds, outfds, erfds = select.select([sys.stdin], [], [], 0) if infds: return True else: return False def inputhook_gevent(): try: while not stdin_ready(): gevent.sleep(0.05) except KeyboardInterrupt: pass return 0 # install the gevent inputhook from IPython.lib.inputhook import inputhook_manager inputhook_manager.set_inputhook(inputhook_gevent) inputhook_manager._current_gui = 'gevent' # First import the embeddable shell class from IPython.frontend.terminal.embed import InteractiveShellEmbed from mock import patch # Update namespace of interactive shell # TODO: Cleanup namespace even further if shell_api is not None: locals().update(shell_api) # Now create an instance of the embeddable shell. The first argument is a # string with options exactly as you would type them if you were starting # IPython at the system command line. Any parameters you want to define for # configuration can thus be specified here. with patch( "IPython.core.interactiveshell.InteractiveShell.init_virtualenv" ): ipshell = InteractiveShellEmbed(config=ipy_config, banner1 =\ """ ____ ________ _ __ ____________ ____ ___ / __ \__ ______ ____ / _/ __ \/ | / / / ____/ ____/ / __ \|__ \\ / /_/ / / / / __ \/ __ \ ______ / // / / / |/ / / / / / / /_/ /__/ / / ____/ /_/ / /_/ / / / / /_____/ _/ // /_/ / /| / / /___/ /___ / _, _// __/ /_/ \__, /\____/_/ /_/ /___/\____/_/ |_/ \____/\____/ /_/ |_|/____/ /____/""", exit_msg = 'Leaving ION shell, shutting down container.') ipshell( 'Pyon (PID: %s) - ION R2 CC interactive IPython shell. Type ionhelp() for help' % os.getpid())
def _start_ipython1(overrides, banner, *, debug=False): try: from IPython.frontend.terminal.embed import InteractiveShellEmbed except ImportError: if debug: print_exc() return None return InteractiveShellEmbed(banner1=banner, user_ns=overrides)
def ishell(self): try: from IPython.frontend.terminal.embed import InteractiveShellEmbed if sys.stdout.isatty(): return InteractiveShellEmbed() except: pass return lambda *v, **k: None
def embedd_ipython011(local_ns={}, global_ns={}): from IPython.config.loader import Config from IPython.frontend.terminal.embed import InteractiveShellEmbed cfg = Config() ipshell = InteractiveShellEmbed(config=cfg, banner1 = IPYTHON_BANNER, exit_msg = IPYTHON_EXIT_MSG) ipshell(local_ns=local_ns, global_ns=global_ns)
def _start_ipython4(overrides, banner, *, debug=False): try: from IPython.terminal.embed import InteractiveShellEmbed shell = InteractiveShellEmbed() except ImportError: if debug: print_exc() return None return partial(shell.mainloop, local_ns=overrides, display_banner=banner)
def run(self, no_ipython, no_bpython): context = self.get_context() if not no_ipython: from IPython.frontend.terminal.embed import InteractiveShellEmbed sh = InteractiveShellEmbed(banner2=self.banner) context = None sh(global_ns=dict(), local_ns=context) return code.interact(self.banner, local=context)
def main(): options, args, proxy = default_main() # pylint: disable=W0612 cfg = Config() cfg.InteractiveShellEmbed.prompt_in1 = "PyArduinoProxy [\\#]> " cfg.InteractiveShellEmbed.prompt_out = "PyArduinoProxy [\\#]: " shell = InteractiveShellEmbed(config=cfg, banner2=banner) shell.user_ns = {} shell()
def run(self, no_ipython): context = self.get_context() if not no_ipython: try: from IPython.frontend.terminal.embed import InteractiveShellEmbed ipython_shell = InteractiveShellEmbed() return ipython_shell(global_ns=dict(), local_ns=context) except ImportError: pass code.interact(self.banner, local=context)
def main(): formatter = logging.Formatter("%(asctime)s %(name)-16s: %(levelname)-8s - %(message)s") parser = argparse.ArgumentParser(description='Process some integers.') parser.add_argument('--logging', action='store', help='display logging messages for specified level') parser.add_argument('--web-server', action='store_true', help='run a standalone WSGI web server with Indico') parser.add_argument('--with-ipv6', action='store_true', help='enable ipv6 support for web server') args, remainingArgs = parser.parse_known_args() if 'logging' in args and args.logging: logger = Logger.get() handler = logging.StreamHandler() handler.setLevel(getattr(logging, args.logging)) handler.setFormatter(formatter) logger.addHandler(handler) if 'web_server' in args and args.web_server: config = Config.getInstance() refserver = RefServer(config.getHostNameURL(), int(config.getPortURL()), enable_ipv6=args.with_ipv6) refserver.run() else: dbi = DBMgr.getInstance() dbi.startRequest() namespace = setupNamespace(dbi) if HAS_IPYTHON: if OLD_IPYTHON: ipshell = IPShellEmbed(remainingArgs, banner=SHELL_BANNER, exit_msg='Good luck', user_ns=namespace) else: config = IPConfig() ipshell = InteractiveShellEmbed(config=config, banner1=SHELL_BANNER, exit_msg='Good luck', user_ns=namespace) ipshell() else: console = code.InteractiveConsole(namespace) console.interact(SHELL_BANNER) dbi.abort() dbi.endRequest()
def run(self, options, args, arduino): try: arduino.ping() except: pass PromptManager.in_template = "PyArduino [\\#]> " PromptManager.out_template = "PyArduino [\\#]: " shell = InteractiveShellEmbed(banner2=banner) shell.user_ns = {} shell()
def run(self, no_ipython): context = self.get_context() if not no_ipython: try: from IPython.frontend.terminal.embed import InteractiveShellEmbed sh = InteractiveShellEmbed(banner1=self.banner) sh(global_ns=dict(), local_ns=context) return except ImportError: pass from code import interact interact(banner=self.banner, local=context)
def _ipsh(): from IPython.frontend.terminal.embed import InteractiveShellEmbed from IPython.config.loader import Config import inspect ipshell = InteractiveShellEmbed(config=Config(), banner1='*** STOP\nCTRL-D to exit', exit_msg='Resume...') 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)
def step(self): self.taskMgr.step() if self.want_shell: self.want_shell = False from IPython.frontend.terminal.embed import InteractiveShellEmbed context = self.__dict__.items() + self.game.__dict__.items() shell = InteractiveShellEmbed(user_ns=dict(context)) from IPython.lib import inputhook # XXX (Mispy): The IPython mainloop runs quite slowly # and causes massive FPS loss. I don't know how to solve # this but I believe it is solvable. inputhook.set_inputhook(self.step) shell() return 0
def interact_ipython(header='', *args, **kwargs): global interact_ipython_ def pre_prompt_hook(_): R.gInterpreter.EndOfLineAction() # Interact is a callable which starts an ipython shell if not interact_ipython_: interact_ipython_ = InteractiveShellEmbed(banner1=UP_LINE) # needed for graphics to work correctly interact_ipython_.set_hook('pre_prompt_hook', pre_prompt_hook) stack_depth = kwargs.pop("stack_depth", 0) + 2 kwargs["stack_depth"] = stack_depth interact_ipython_(header, *args, **kwargs)
def sh(banner): """Wrapper around interactive ipython shell that factors out ipython version depencies. """ import IPython if hasattr(IPython, 'release') and \ map(int, IPython.release.version.split('.')) >= [0, 11]: from IPython.frontend.terminal.embed \ import InteractiveShellEmbed InteractiveShellEmbed(banner1=banner)() else: from IPython.Shell import IPShellEmbed IPShellEmbed(banner=banner)()
def gambit_shell(): """ Start an ipython session after initializing the environment """ import gambit import gambit.nash import gambit.qre # Everything in this dictionary will be added to the top-level # namespace in the shell. ns = {'gambit': gambit, 'nash': gambit.nash, 'qre': gambit.qre} shell = InteractiveShellEmbed() shell.user_ns = ns shell()
def shell(store, options, jugspace): ''' shell(store, options, jugspace) Implement 'shell' command. Currently depends on Ipython being installed. ''' try: from IPython.frontend.terminal.embed import InteractiveShellEmbed from IPython.frontend.terminal.ipapp import load_default_config config = load_default_config() ipshell = InteractiveShellEmbed(config=config, display_banner=_ipython_banner) except ImportError: try: # Fallback for older Python: from IPython.Shell import IPShellEmbed ipshell = IPShellEmbed(banner=_ipython_banner) except ImportError: import sys sys.stderr.write(_ipython_not_found_msg) sys.exit(1) def _load_all(): ''' load_all() Loads all task results. ''' load_all(jugspace, local_ns) local_ns = { 'load_all': _load_all, 'value': value, } # This is necessary for some versions of Ipython. See: # http://groups.google.com/group/pylons-discuss/browse_thread/thread/312e3ead5967468a try: del jugspace['__builtins__'] except KeyError: pass jugspace.update(local_ns) local_ns['__name__'] = '__jugfile__' ipshell(global_ns=jugspace, local_ns=local_ns)
def launch_shell(self, argv=[]): # Configure prompts and messages in_template = 'L2A: In <\\#>: ' in_template2 = ' .\\D.:' out_template = 'L2A: Out<\\#>: ' banner = '*** Launcing L2 Analysis Shell ***\nAvailable analysis routines:\n%s' % self.formatted_routine_names( ) exit_msg = '*** Bye ***' # Set pylab environment as interactive pylab.interactive(True) # Try using an older version of IPython first try: argv += [ '-pi1', in_template, '-pi2', in_template2, '-po', out_template ] from IPython.Shell import IPShellEmbed ipshell = IPShellEmbed(argv, banner=banner, exit_msg=exit_msg) ipshell(local_ns=self._local_namespace, global_ns=self._global_namespace) except ImportError as imp_err: # Newer version of IPython, 0.11 onward use this interface from IPython.config.loader import Config cfg = Config() prompt_config = cfg.PromptManager prompt_config.in_template = in_template prompt_config.in2_template = in_template2 prompt_config.out_template = out_template from IPython.frontend.terminal.embed import InteractiveShellEmbed ipshell = InteractiveShellEmbed(config=cfg, banner1=banner, exit_msg=exit_msg) # There is no access to global namespace in this version of IPython # put everything into the local namespace namespace = {} namespace.update(self._local_namespace) namespace.update(self._global_namespace) ipshell(local_ns=namespace)
def action(ipython=use_ipython): """Start a new interactive python session.""" namespace = init_func() if ipython: try: try: from IPython.frontend.terminal.embed import InteractiveShellEmbed sh = InteractiveShellEmbed(banner1=banner) except ImportError: from IPython.Shell import IPShellEmbed sh = IPShellEmbed(banner=banner) except ImportError: pass else: sh(global_ns={}, local_ns=namespace) return from code import interact interact(banner, local=namespace)