def interface_shell_embed(interface): """ Returns an IPython shell which uses a Sage interface on the backend to perform the evaluations. It uses :class:`InterfaceShellTransformer` to transform the input into the appropriate ``interface.eval(...)`` input. EXAMPLES:: sage: from sage.misc.interpreter import interface_shell_embed sage: shell = interface_shell_embed(gap) sage: shell.run_cell('List( [1..10], IsPrime )') [ false, true, true, false, true, false, true, false, false, false ] """ try: cfg = Config(get_ipython().config) except NameError: cfg = Config(DEFAULT_SAGE_CONFIG) cfg.PromptManager['in_template'] = interface.name() + ': ' ipshell = InteractiveShellEmbed(config=cfg, banner1='\n --> Switching to %s <--\n\n'%interface, exit_msg = '\n --> Exiting back to Sage <--\n') ipshell.interface = interface while ipshell.prefilter_manager.transformers: ipshell.prefilter_manager.transformers.pop() while ipshell.prefilter_manager.checkers: ipshell.prefilter_manager.checkers.pop() ipshell.ex('from sage.all import *') InterfaceShellTransformer(shell=ipshell, prefilter_manager=ipshell.prefilter_manager, config=cfg) return ipshell
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 run(self, options, args, arduino): PromptManager.in_template = "PyArduino [\\#]> " PromptManager.out_template = "PyArduino [\\#]: " shell = InteractiveShellEmbed(banner2=banner) shell.user_ns = {} shell()
def main(): # Load the UAVO xml files in the workspace import taulabs uavo_defs = taulabs.uavo_collection.UAVOCollection() uavo_defs.from_uavo_xml_path('shared/uavobjectdefinition') # Build a new module that will make up the global namespace for the # interactive shell. This allows us to restrict what the ipython shell sees. import imp user_module = imp.new_module('taulabs_env') user_module.__dict__.update({ 'operator' : __import__('operator'), }) # Extend the shell environment to include all of the uavo.UAVO_* classes that were # auto-created when the uavo xml files were processed. uavo_classes = [(t[0], t[1]) for t in taulabs.uavo.__dict__.iteritems() if 'UAVO_' in t[0]] user_module.__dict__.update(uavo_classes) # Build the "user" (ie. local) namespace that the interactive shell # will see. These variables show up in the output of "%whos" in the shell. user_ns = { 'uavo_defs' : uavo_defs, } import IPython from IPython.frontend.terminal.embed import InteractiveShellEmbed e = InteractiveShellEmbed(user_ns = user_ns, user_module = user_module) e.enable_pylab(import_all = True) e("Have a look around. Your UAVO definitions are in 'uavo_defs'.")
def invoke(cls, ns, banner): # pragma: nocover """ :param ns: local namespace :param banner: interactive shell startup banner Embed an interactive ipython shell. Try the InteractiveShellEmbed API first, fall back on IPShellEmbed for older IPython versions. """ try: from IPython.frontend.terminal.embed import ( InteractiveShellEmbed ) # try and load their default profile from IPython.frontend.terminal.ipapp import ( load_default_config ) config = load_default_config() shell = InteractiveShellEmbed(config=config, banner2=banner) shell(local_ns=ns) except ImportError: # Support for the IPython <= 0.10 shell API from IPython.Shell import IPShellEmbed shell = IPShellEmbed(argv=[]) shell.set_banner(shell.IP.BANNER + '\n\n' + banner) shell(local_ns=ns, global_ns={})
def run_ipython(): import IPython from IPython.frontend.terminal.embed import InteractiveShellEmbed from django.conf import settings try: imported_objects = import_objects(options, self.style) cfgfile = "%s/.config/ipython/profile_default/ipython_config.py" % os.environ['HOME'] cfg = IPython.config.loader.PyFileConfigLoader(cfgfile).load_config() appname = "Welcome to the %s Shell.\n" % getattr(settings, "APPLICATION_NAME", "") ipshell = InteractiveShellEmbed(config=cfg, banner1=appname, user_ns=imported_objects) # An example how to define magics # the function _toggle_logging has to be provided by the PYTHONSTARTUP script, # see django_extensions/management/shells.py try: ipshell.define_magic('toggle_logging', imported_objects['_toggle_logging']) except: pass ipshell() except ImportError: # IPython < 0.11 # Explicitly pass an empty list as arguments, because otherwise # IPython would use sys.argv from this script. # Notebook not supported for IPython < 0.11. from IPython.Shell import IPShell imported_objects = import_objects(options, self.style) shell = IPShell(argv=[], user_ns=imported_objects) shell.mainloop()
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 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 setupIpython(): try: import IPython from IPython.config.loader import Config from IPython.frontend.terminal.embed import InteractiveShellEmbed cfg = Config() cfg.PromptManager.in_template = "BinPy:\\#> " cfg.PromptManager.out_template = "BinPy:\\#: " bpyShell = InteractiveShellEmbed(config=cfg, banner1=banner, exit_msg=exit_msg) bpyShell.define_magic("clear", magic_clear) except ImportError: try: from IPython.Shell import IPShellEmbed argsv = [ '-pi1', 'BinPY:\\#>', '-pi2', ' .\\D.:', '-po', 'BinPy:\\#>', '-nosep' ] bpyShell = IPShellEmbed(argsv) bpyShell.set_banner(banner) bpyShell.set_exit_msg(exit_msg) except ImportError: raise return bpyShell()
def interact_ipython(header='', *args, **kwargs): 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 interact_ipython_(header, *args, **kwargs)
def setupIpython(): try: import IPython from IPython.config.loader import Config from IPython.frontend.terminal.embed import InteractiveShellEmbed cfg = Config() cfg.PromptManager.in_template = "BinPy:\\#> " cfg.PromptManager.out_template = "BinPy:\\#: " bpyShell = InteractiveShellEmbed(config=cfg, banner1=banner, exit_msg=exit_msg) bpyShell.define_magic("clear", magic_clear) except ImportError: try: from IPython.Shell import IPShellEmbed argsv = ['-pi1', 'BinPY:\\#>', '-pi2', ' .\\D.:', '-po', 'BinPy:\\#>', '-nosep'] bpyShell = IPShellEmbed(argsv) bpyShell.set_banner(banner) bpyShell.set_exit_msg(exit_msg) except ImportError: raise return bpyShell()
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 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 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 main(): parser = argparse.ArgumentParser( description='An ipython shell, useful for testing and exploring aqdb') parser.add_argument('-v', action='count', dest='verbose', help='increase verbosity by adding more (-vv), etc.') opts = parser.parse_args() if opts.verbose >= 1: db.engine.echo = True if db.engine.url.drivername == 'sqlite': prompt = str(db.engine.url).split('///')[1] else: # couldn't use the underlying dbapi connection.current_schema # from the engine as it too is '' user = db.engine.url.username or os.environ.get("USER") host = db.engine.url.host or 'LOCALHOST' prompt = '%s@%s' % (user, host) if db.engine.url.database: prompt += '/%s' prompt += '> ' ipycfg = IPyConfig() ipycfg.PromptManager.in_template = prompt ipycfg.PlaintextFormatter.pprint = True ipycfg.InteractiveShell.separate_in = '' ipycfg.InteractiveShell.separate_out = '' ipycfg.InteractiveShell.separate_out2 = '' ipycfg.InteractiveShell.colors = 'Linux' ipshell = InteractiveShellEmbed(config=ipycfg, banner1=_banner) 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(): loop = asyncio.get_event_loop() session = aiohttp.ClientSession() async def before_start(session): ws = await session.ws_connect("ws://0.0.0.0:8000/chat") return ws ws = loop.run_until_complete(before_start(loop)) local_vars = locals() local_vars['ws'] = ws def send_str(s): async def run(s): res = await ws.send_str(s) return res res = loop.run_until_complete(run(s)) return res local_vars['send_str'] = send_str try: from IPython.frontend.terminal.embed import InteractiveShellEmbed ipshell = InteractiveShellEmbed() ipshell() except ImportError: import code pyshell = code.InteractiveConsole(locals=local_vars) pyshell.interact()
def start_python_console(namespace=None, noipython=False, banner=''): """Start Python console binded to the given namespace. If IPython is available, an IPython console will be started instead, unless `noipython` is True. Also, tab completion will be used on Unix systems. """ if namespace is None: namespace = {} try: try: # use IPython if available if noipython: raise ImportError() try: from IPython.frontend.terminal.embed import InteractiveShellEmbed sh = InteractiveShellEmbed(banner1=banner) except ImportError: from IPython.Shell import IPShellEmbed sh = IPShellEmbed(banner=banner) sh(global_ns={}, local_ns=namespace) except ImportError: import code try: # readline module is only available on unix systems import readline except ImportError: pass else: import rlcompleter readline.parse_and_bind("tab:complete") code.interact(banner=banner, local=namespace) except SystemExit: # raised when using exit() in python code.interact pass
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 shell(no_ipython): """Start a new interactive python session.""" banner = ('\nWelcome to the interactive shell environment of LodgeIt!\n' '\n' 'You can use the following predefined objects: app, local, db.\n' 'To run the application (creates a request) use *run_app*.') namespace = make_shell() if not no_ipython: try: try: from IPython.frontend.terminal.embed import InteractiveShellEmbed sh = InteractiveShellEmbed.instance(banner1=banner) except ImportError: from IPython.Shell import IPShellEmbed sh = IPShellEmbed(banner=banner) except ImportError: pass else: sh(local_ns=namespace) return from code import interact interact(banner, local=namespace)
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 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 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 main(self): # 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 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 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 interact(): cfg = Config() ipshell = InteractiveShellEmbed(config=cfg, banner1="Androlyze version %s" % androconf.ANDROGUARD_VERSION) init_print_colors() ipshell()
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 ishell(self): try: from IPython.frontend.terminal.embed import InteractiveShellEmbed if sys.stdout.isatty(): return InteractiveShellEmbed() except: pass return lambda *v, **k: None
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 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 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, 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 interface_shell_embed(interface): """ Returns an IPython shell which uses a Sage interface on the backend to perform the evaluations. It uses :class:`InterfaceShellTransformer` to transform the input into the appropriate ``interface.eval(...)`` input. INPUT: - ``interface`` -- A Sage ``PExpect`` interface instance. EXAMPLES:: sage: from sage.misc.interpreter import interface_shell_embed sage: shell = interface_shell_embed(gap) sage: shell.run_cell('List( [1..10], IsPrime )') [ false, true, true, false, true, false, true, false, false, false ] """ try: cfg = Config(get_ipython().config) except NameError: cfg = Config(DEFAULT_SAGE_CONFIG) cfg.PromptManager['in_template'] = interface.name() + ': ' ipshell = InteractiveShellEmbed( config=cfg, banner1='\n --> Switching to %s <--\n\n' % interface, exit_msg='\n --> Exiting back to Sage <--\n') ipshell.interface = interface while ipshell.prefilter_manager.transformers: ipshell.prefilter_manager.transformers.pop() while ipshell.prefilter_manager.checkers: ipshell.prefilter_manager.checkers.pop() ipshell.ex('from sage.all import *') InterfaceShellTransformer(shell=ipshell, prefilter_manager=ipshell.prefilter_manager, config=cfg) return ipshell
def start_shell(self, msg = ""): status_msg = [] status_msg.append(msg) #load convenient modules self.user_ns['time'] = time #find the available devices items = self.config._device_cache.items() items.sort() status_msg.append("Available devices:") for name, device in items: status_msg.append("\t%s" % name) #add device name to the user name space self.user_ns[name] = device #find the available controllers items = self.config._controller_cache.items() items.sort() status_msg.append("Available controllers:") for name, controller in items: status_msg.append("\t%s" % name) #add controller name to the user name space self.user_ns[name] = controller #add all the special commands to the namespace self.user_ns.update(self.commands) #complete the status message status_msg.append('') status_msg.append("-- Hit Ctrl-D to exit. --") status_msg = '\n'.join(status_msg) #start the shell ipshell = None # try: ipshell = IPYTHON_SHELL(user_ns = self.user_ns, banner1 = status_msg) #FIXME change made for ipython >= 0.13 #set up hooks ipshell.set_hook('shutdown_hook',self.shutdown_hook) ipshell.mainloop() #FIXME change made for ipython >= 0.13
def run_shell(self, *args): locs = dict(__name__="aptgregator-admin", wsgiapp=self.wsgiapp, app=self.app) admin_boot = os.path.join(os.path.dirname(__file__), 'admin_boot.py') execfile(admin_boot, {}, locs) if self.options.script_file: execfile(self.options.script_file, {}, locs) return try: # try to use IPython if possible if self.options.disable_ipython: raise ImportError() from IPython.frontend.terminal.embed import InteractiveShellEmbed if self.options.verbose: shell = InteractiveShellEmbed() print '' else: shell = InteractiveShellEmbed(banner1='') shell(local_ns=locs, global_ns={}) except ImportError: import code shell = code.InteractiveConsole(locals=locs) if self.options.verbose: banner = 'Python %s\n\n' % sys.version else: banner = '' try: import readline except ImportError: pass print '' shell.interact(banner)
def setup_shell(): banner = "+----------------------------------------------------------------------+\n" banner += " PML Shell - built on IPython.\n" banner += "+----------------------------------------------------------------------+\n" banner += "Commands: \n" banner += "\t'tutorial' will begin the interactive tutorial.\n" banner += "\t'tutorial list' will display individual lessons in the tutorial.\n" banner += "\t'docs' will open up the online documentation in a web browser.\n" banner += "\t'exit', 'quit' or press 'CTRL + D' to exit the shell.\n" exit_message = "\n* Exiting PML shell, good bye! *\n" # XXX: this currently only supports IPython version 0.11 or higher! config = Config() config.PromptManager.in_template = "pml:\\#> " config.PromptManager.out_template = "pml:\\#: " pml_shell = InteractiveShellEmbed(config=config, banner1=banner, exit_msg=exit_message) pml_shell.define_magic("tutorial", magic_tutorial) pml_shell.define_magic("docs", magic_docs) return pml_shell
def main(): uavo_list = telemetry.get_telemetry_by_args() # retrieve the time from the first object.. also guarantees we can parse base_time = next(iter(uavo_list)).time # Build a new module that will make up the global namespace for the # interactive shell. This allows us to restrict what the ipython shell sees. import imp user_module = imp.new_module('dronin_env') user_module.__dict__.update({ 'operator' : __import__('operator'), 'base_time' : base_time, }) # Build the "user" (ie. local) namespace that the interactive shell # will see. These variables show up in the output of "%whos" in the shell. user_ns = { 'base_time' : base_time, 'log_file' : uavo_list.filename, 'githash' : uavo_list.githash, 'uavo_defs' : uavo_list.uavo_defs, 'uavo_list' : uavo_list, } # Extend the shell environment to include all of the uavo.UAVO_* classes that were # auto-created when the uavo xml files were processed. uavo_classes = [(t[0], t[1]) for t in uavo.__dict__.iteritems() if 'UAVO_' in t[0]] user_module.__dict__.update(uavo_classes) # Instantiate an ipython shell to interact with the log data. import IPython from IPython.frontend.terminal.embed import InteractiveShellEmbed e = InteractiveShellEmbed(user_ns = user_ns, user_module = user_module) e.enable_pylab(import_all = True) e("Analyzing log file: %s" % uavo_list.filename)
def _12shell(vars, message, prompt, exit_msg): #prompt_message = "Welcome! Useful: G is the graph, DB, C" prompt_message = message from IPython.frontend.terminal.embed import InteractiveShellEmbed from IPython.config.loader import Config cfg = Config() # cfg.InteractiveShellEmbed.prompt_in1="pylans:ipy> " cfg.PromptManager.in_template="myprompt:> " # cfg.InteractiveShellEmbed.prompt_out="myprompt [\\#]: " cfg.InteractiveShellEmbed.profile="pysh" ipshell = InteractiveShellEmbed.instance(config=cfg, user_ns=vars, banner2=message, exit_msg=exit_msg) return ipshell
def shell(no_ipython): """Start a new interactive python session.""" banner = 'Interactive Werkzeug Shell' namespace = make_shell() if not no_ipython: try: try: from IPython.frontend.terminal.embed import InteractiveShellEmbed sh = InteractiveShellEmbed.instance(banner1=banner) except ImportError: from IPython.Shell import IPShellEmbed sh = IPShellEmbed(banner=banner) except ImportError: pass else: sh(local_ns=namespace) return from code import interact interact(banner, local=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.instance(banner1=banner) except ImportError: from IPython.Shell import IPShellEmbed sh = IPShellEmbed(banner=banner) except ImportError: pass else: sh(local_ns=namespace) return from code import interact interact(banner, local=namespace)
def __init__(self,argv=None,user_ns=None,user_global_ns=None, cin=None, cout=None,cerr=None, input_func=None): if argv is None: argv=[] # This is to get rid of the blockage that occurs during # IPython.Shell.InteractiveShell.user_setup() #IPython.iplib.raw_input = lambda x: None # not used? #self.term = IPython.genutils.IOTerm(cin=cin, cout=cout, cerr=cerr) from IPython.config.loader import Config cfg = Config() cfg.InteractiveShell.colors = "Linux" os.environ['TERM'] = 'dumb' excepthook = sys.excepthook self.IP = InteractiveShellEmbed(config=cfg, user_ns=user_ns, user_global_ns=user_global_ns) self.IP.system = lambda cmd: self.shell(self.IP.var_expand(cmd), header='IPython system call: ', verbose=self.IP.rc.system_verbose) if cin: IPython.utils.io.stdin = IPython.utils.io.IOStream(cin) if cout: IPython.utils.io.stdout = IPython.utils.io.IOStream(cout) if cerr: IPython.utils.io.stderr = IPython.utils.io.IOStream(cerr) if input_func: IPython.frontend.terminal.interactiveshell.raw_input_original = input_func sys.excepthook = excepthook self.iter_more = False self.history_level = 0 self.complete_sep = re.compile('[\s\{\}\[\]\(\)]')
def _run_shell(self, base_module, locs, disable_ipython): banner = " All objects from %s are available\n" % base_module banner += " Additional Objects:\n" banner += " %-10s - %s\n" % ('wsgiapp', "This project's WSGI App instance") banner += " %-10s - %s\n" % ('app', 'WebTest.TestApp wrapped around wsgiapp') try: if disable_ipython: raise ImportError() # try to use IPython if possible try: # ipython >= 0.11 from IPython.frontend.terminal.embed import InteractiveShellEmbed shell = InteractiveShellEmbed(banner2=banner) except ImportError: # ipython < 0.11 from IPython.Shell import IPShellEmbed shell = IPShellEmbed() shell.set_banner(shell.IP.BANNER + '\n\n' + banner) shell(local_ns=locs, global_ns={}) except ImportError: import code py_prefix = sys.platform.startswith('java') and 'J' or 'P' newbanner = "TurboGears2 Interactive Shell\n%sython %s\n\n" % \ (py_prefix, sys.version) banner = newbanner + banner shell = code.InteractiveConsole(locals=locs) try: import readline except ImportError: pass shell.interact(banner)
from IPython.frontend.terminal.embed import InteractiveShellEmbed have_ipython = True except ImportError: interact = interact_plain else: # ROOT has a bug causing it to print (Bool_t)1 to the console. # This is fixed in defaults.py if rootpy is imported under the ipython # interpreter, but at this point that is too late, so we need to try again _finalSetup = getattr(R.__class__, "_ModuleFacade__finalSetup", None) if _finalSetup: _orig_func = getattr(_finalSetup, "_orig_func", None) if _orig_func: _finalSetup = _orig_func fix_ipython_startup(_finalSetup) # Interact is a callable which starts an ipython shell interact_ipython_ = InteractiveShellEmbed(banner1=UP_LINE) # needed for graphics to work correctly def pre_prompt_hook(_): R.gInterpreter.EndOfLineAction() interact_ipython_.set_hook('pre_prompt_hook', pre_prompt_hook) def interact_ipython(header='', *args, **kwargs): stack_depth = kwargs.pop("stack_depth", 0) + 2 interact_ipython_(header, *args, **kwargs) interact = interact_ipython
def gnubg_InteractivePyShell_tui(argv=[''], banner=None): global supports_readline import sys import traceback import code try: sys.argv = argv # Check for IPython as it is generally the best cmdline interpreter from IPython.frontend.terminal.embed import InteractiveShellEmbed from IPython import __version__ as ipyversion from IPython.config.loader import Config except: # Otherwise use standard interpreter if (banner == None): banner = 'Python ' + sys.version if (supports_readline): try: # See if we can use readline support import readline except: # Might be Win32 so check for pyreadline try: import pyreadline as readline except: pass try: # See if we can add tab completion import rlcompleter readline.parse_and_bind('tab: complete') except: pass try: code.interact(banner=banner, local=globals()) except SystemExit: # Ignore calls to exit() and quit() pass return True else: # If we get this far we are on Win32 and too early # a version to support the embedded interpreter so # we simulate one print banner print '<Control-Z> and <Return> to exit' while True: print '>>> ', line = sys.stdin.readline() if not line: break try: exec(line) except SystemExit: # Ignore calls to exit() and quit() break return True try: # Launch IPython interpreter cfg = Config() prompt_config = cfg.PromptManager prompt_config.in_template = 'In <\\#> > ' prompt_config.in2_template = ' .\\D. > ' prompt_config.out_template = 'Out<\\#> > ' cfg.InteractiveShell.confirm_exit = False if banner == None: banner = 'IPython ' + ipyversion + ', Python ' + sys.version # We want to execute in the name space of the CALLER of this function, # not within the namespace of THIS function. # This allows us to have changes made in the IPython environment # visible to the CALLER of this function # Go back one frame and get the locals. call_frame = sys._getframe(0).f_back calling_ns = call_frame.f_locals ipshell = InteractiveShellEmbed( config=cfg, user_ns=calling_ns, banner1=banner) try: ipshell() except SystemExit: # Ignore calls to exit() and quit() pass # Cleanup the sys environment (including exception handlers) ipshell.restore_sys_module_state() return True except: traceback.print_exc() return False
def process_argv(argv): """ Process command-line arguments (minus argv[0]!), rearrange and execute. """ # Initial preparation import __main__ for (k,v) in global_constants.items(): exec '%s = %s' % (k,v) in __main__.__dict__ exec_startup_files() # Repeatedly process options, if any, followed by filenames, if any, until nothing is left topo_parser.disable_interspersed_args() args=argv option=None global something_executed while True: # Process options up until the first filename (option,args) = topo_parser.parse_args(args,option) # Handle filename if args: filename=args.pop(0) #print "Executing %s" % (filename) filedir = os.path.dirname(os.path.abspath(filename)) sys.path.insert(0,filedir) # Allow imports relative to this file's path sim_name_from_filename(filename) # Default value of topo.sim.name execfile(filename,__main__.__dict__) something_executed=True if not args: break global_params.check_for_unused_names() # If no scripts and no commands were given, pretend -i was given. if not something_executed: interactive() if option.gui: topo.guimain.title(topo.sim.name) ## INTERACTIVE SESSION BEGINS HERE (i.e. can't have anything but ## some kind of cleanup code afterwards) if os.environ.get('PYTHONINSPECT'): print BANNER # CBALERT: should probably allow a way for users to pass # things to IPython? Or at least set up some kind of # topographica ipython config file. Right now, a topo_parser # option has to be added for every ipython option we want to # support (e.g. see --pdb) if ipython: if ipython == "0.10": # Stop IPython namespace hack? # http://www.nabble.com/__main__-vs-__main__-td14606612.html __main__.__name__="__mynamespace__" ipython_args = ['-noconfirm_exit','-nobanner', '-pi1',CommandPrompt.get_format(), '-pi2',CommandPrompt2.get_format(), '-po',OutputPrompt.get_format()] if option.pdb: ipython_args.append('-pdb') ipshell = IPShell( ipython_args, user_ns=__main__.__dict__, ) ipshell.mainloop(sys_exit=1) elif ipython == "0.11": config = Config() config.InteractiveShell.prompt_in1 = CommandPrompt.get_format() config.InteractiveShell.prompt_in2 = CommandPrompt2.get_format() config.InteractiveShell.prompt_out = OutputPrompt.get_format() config.InteractiveShell.confirm_exit = False ipshell = IPShell( config=config, user_ns=__main__.__dict__, banner1="", exit_msg="", ) ipshell() sys.exit()
else: if not plain: if bpython: try: import bpython bpython.embed(locals_=_env) return except: logger.warning( 'import bpython error; trying ipython...') else: try: import IPython if IPython.__version__ >= '0.11': from IPython.frontend.terminal.embed import InteractiveShellEmbed shell = InteractiveShellEmbed(user_ns=_env) shell() return else: # following 2 lines fix a problem with # IPython; thanks Michael Toomim if '__builtins__' in _env: del _env['__builtins__'] shell = IPython.Shell.IPShell(argv=[], user_ns=_env) shell.mainloop() return except: logger.warning( 'import IPython error; use default python shell') enable_autocomplete_and_history(adir,_env) code.interact(local=_env)
#!/usr/bin/env python # # A interactive shell for inspecting the SkyLines data model. # import sys import os from config import to_envvar sys.path.append(os.path.dirname(sys.argv[0])) conf_path = len(sys.argv) > 1 and sys.argv[1] if not to_envvar(conf_path): sys.exit('Config file "{}" not found.'.format(conf_path)) from IPython.config.loader import Config from IPython.frontend.terminal.embed import InteractiveShellEmbed from skylines import app from skylines.model import * config = Config() shell = InteractiveShellEmbed(config=config) shell.push(globals()) shell('SkyLines Shell')
from IPython.frontend.terminal.embed import InteractiveShellEmbed banner2 = None if os.name == 'nt': # Patching IPython to avoid enabling readline: # we can't simply disable readline in IPython options because # it would also mean no text coloring support in terminal from IPython.core.interactiveshell import InteractiveShell, io def patched_init_io(self): io.stdout = io.IOStream(sys.stdout) io.stderr = io.IOStream(sys.stderr) InteractiveShell.init_io = patched_init_io banner2 = """Warning: Spyder does not support GUI interactions with IPython >=v0.11 on Windows platforms (only IPython v0.10 is fully supported). """ __ipythonshell__ = InteractiveShellEmbed(banner2=banner2)#, # display_banner=False) # __ipythonshell__.shell.show_banner() # __ipythonshell__.enable_pylab(gui='qt') #TODO: parse command line options using the two lines commented # above (banner has to be shown afterwards) #FIXME: Windows platforms: pylab/GUI loop support is not working __ipythonshell__.stdin_encoding = os.environ['SPYDER_ENCODING'] del banner2 except ImportError: # IPython v0.10 import IPython.Shell __ipythonshell__ = IPython.Shell.start() __ipythonshell__.IP.stdin_encoding = os.environ['SPYDER_ENCODING'] __ipythonshell__.IP.autoindent = 0
prompt_config.out_template = 'Out<\\#>: ' else: print "Running nested copies of IPython." print "The prompts for the nested copy have been modified" cfg = Config() nested = 1 # First import the embeddable shell class 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.') # Make a second instance, you can have as many as you want. cfg2 = cfg.copy() prompt_config = cfg2.PromptManager prompt_config.in_template = 'In2<\\#>: ' if not nested: prompt_config.in_template = 'In2<\\#>: ' prompt_config.in2_template = ' .\\D.: ' prompt_config.out_template = 'Out<\\#>: ' ipshell2 = InteractiveShellEmbed(config=cfg, banner1 = 'Second IPython instance.') print '\nHello. This is printed from the main controller program.\n'
def main(): # Setup the command line arguments. parser = argparse.ArgumentParser(usage = USAGE, description = DESC) # Log format indicates this log is using the old file format which # embeds the timestamping information between the UAVTalk packet # instead of as part of the packet parser.add_argument("-t", "--timestamped", action = 'store_false', default = True, help = "indicate that this is an overo log file or some format that has timestamps") parser.add_argument("-g", "--githash", action = "store", dest = "githash", help = "override githash for UAVO XML definitions") parser.add_argument("-v", "--viewer", action = 'store_true', default = False, dest = "viewer", help = "launch the log viewer gui") parser.add_argument("sources", nargs = "+", help = "list of log files for processing") # Parse the command-line. args = parser.parse_args() # Process the source files. for src in args.sources: print "Reading Log file: %s" % src # Open the log file src = normalize_path(src) import cPickle as pickle try: pickle_name = src + '.pickle' pickle_fd = open(pickle_name, 'rb') githash = pickle.load(pickle_fd) uavo_parsed = pickle.load(pickle_fd) pickle_fd.close() print "Recovered %d log entries from git hash '%s' pickled log file '%s'" % (len(uavo_parsed), githash, pickle_name) pickle_data_loaded = True except: pickle_data_loaded = False if not pickle_data_loaded: fd = open(src, "rb") if args.githash is not None: githash = args.githash else: # If we specify the log header no need to attempt to parse it # Check the header signature # First line is "Tau Labs git hash:" # Second line is the actual git hash # Third line is the UAVO hash # Fourth line is "##" sig = fd.readline() if sig != 'Tau Labs git hash:\n': print "Source file does not have a recognized header signature" print '|' + sig + '|' sys.exit(2) # Determine the git hash that this log file is based on githash = fd.readline()[:-1] if githash.find(':') != -1: import re githash = re.search(':(\w*)\W', githash).group(1) print "Log file is based on git hash: %s" % githash uavohash = fd.readline() divider = fd.readline() print "Exporting UAVO XML files from git repo" import taulabs uavo_defs = taulabs.uavo_collection.UAVOCollection() uavo_defs.from_git_hash(githash) print "Found %d unique UAVO definitions" % len(uavo_defs) parser = taulabs.uavtalk.UavTalk(uavo_defs) base_time = None if not pickle_data_loaded: print "Parsing using the LogFormat: " + `args.timestamped` print "Reading log file..." uavo_parsed = [] while fd: try: if args.timestamped and parser.state == taulabs.uavtalk.UavTalk.STATE_COMPLETE: # This logging format is somewhat of a hack and simply prepends additional # information in front of each UAVTalk packet. We look for this information # whenever the parser has completed a packet. Note that there is no checksum # applied to this information so it can be totally messed up, especially if # there is a frame shift error. The internal timestamping method of UAVTalk is # a much better idea. from collections import namedtuple LogHeader = namedtuple('LogHeader', 'time size') # Read the next log record header log_hdr_fmt = "<IQ" log_hdr_data = fd.read(struct.calcsize(log_hdr_fmt)) # Check if we hit the end of the file if len(log_hdr_data) == 0: # Normal End of File (EOF) at a record boundary break # Got a log record header. Unpack it. log_hdr = LogHeader._make(struct.unpack(log_hdr_fmt, log_hdr_data)) # Set the baseline timestamp from the first record in the log file if base_time is None: base_time = log_hdr.time parser.processByte(ord(fd.read(1))) if parser.state == taulabs.uavtalk.UavTalk.STATE_COMPLETE: if args.timestamped: u = parser.getLastReceivedObject(timestamp=log_hdr.time) else: u = parser.getLastReceivedObject() if u is not None: uavo_parsed.append(u) except TypeError: print "End of file" break fd.close() print "Processed %d Log File Records" % len(uavo_parsed) print "Writing pickled log file to '%s'" % pickle_name import cPickle as pickle pickle_fd = open(pickle_name, 'wb') pickle.dump(githash, pickle_fd) pickle.dump(uavo_parsed, pickle_fd) pickle_fd.close() print "Converting log records into python objects" uavo_list = taulabs.uavo_list.UAVOList(uavo_defs) for obj_id, data, timestamp in uavo_parsed: obj = uavo_defs[obj_id] u = obj.instance_from_bytes(data, timestamp) uavo_list.append(u) # We're done with this (potentially very large) variable, delete it. del uavo_parsed # Build a new module that will make up the global namespace for the # interactive shell. This allows us to restrict what the ipython shell sees. import imp user_module = imp.new_module('taulabs_env') user_module.__dict__.update({ 'operator' : __import__('operator'), 'base_time' : base_time, }) # Build the "user" (ie. local) namespace that the interactive shell # will see. These variables show up in the output of "%whos" in the shell. user_ns = { 'base_time' : base_time, 'log_file' : src, 'githash' : githash, 'uavo_defs' : uavo_defs, 'uavo_list' : uavo_list, } # Extend the shell environment to include all of the uavo.UAVO_* classes that were # auto-created when the uavo xml files were processed. uavo_classes = [(t[0], t[1]) for t in taulabs.uavo.__dict__.iteritems() if 'UAVO_' in t[0]] user_module.__dict__.update(uavo_classes) if args.viewer: # Start the log viwer app from PyQt4 import QtGui from logviewer.gui import Window app = QtGui.QApplication(sys.argv) main = Window() main.show() main.plot(uavo_list, uavo_defs) sys.exit(app.exec_()) else: # Instantiate an ipython shell to interact with the log data. import IPython from IPython.frontend.terminal.embed import InteractiveShellEmbed e = InteractiveShellEmbed(user_ns = user_ns, user_module = user_module) e.enable_pylab(import_all = True) e("Analyzing log file: %s" % src)
#!/usr/bin/env python import IPython import fsm.config.db import fsm.config.app as app_config #import arkplatform2.models_sql as model from fsm.models import * import sys from IPython.frontend.terminal.embed import InteractiveShellEmbed if __name__ == "__main__": print "=== Welcome to SNAC Merge Tool Shell (%s env) ===" % "dev" init_model(fsm.config.db.get_db_uri()) shell = InteractiveShellEmbed() shell.user_ns = {} shell()
def process_argv(argv): """ Process command-line arguments (minus argv[0]!), rearrange and execute. """ # Initial preparation import __main__ for (k,v) in global_constants.items(): exec '%s = %s' % (k,v) in __main__.__dict__ exec_startup_files() # Repeatedly process options, if any, followed by filenames, if any, until nothing is left topo_parser.disable_interspersed_args() args=argv option=None global something_executed while True: # Process options up until the first filename (option,args) = topo_parser.parse_args(args,option) # Handle filename if args: filename=args.pop(0) #print "Executing %s" % (filename) filedir = os.path.dirname(os.path.abspath(filename)) sys.path.insert(0,filedir) # Allow imports relative to this file's path sim_name_from_filename(filename) # Default value of topo.sim.name execfile(filename,__main__.__dict__) something_executed=True if not args: break global_params.check_for_unused_names() # OpenMP settings and defaults openmp_threads = __main__.__dict__.get('openmp_threads') if (openmp_threads is None): openmp_threads=-1 openmp_min_threads = __main__.__dict__.get('openmp_min_threads') if (openmp_min_threads is None): openmp_min_threads=2 openmp_max_threads = __main__.__dict__.get('openmp_max_threads') if (openmp_threads != 1): # OpenMP is disabled if openmp_threads == 1 (num_threads, total_cores) = get_omp_num_threads(openmp_threads, openmp_min_threads, openmp_max_threads) if num_threads is None: print "OpenMP: Using OMP_NUM_THREADS environment variable if set. Otherwise, all cores in use." elif num_threads == 'NSLOTS': os.environ['OMP_NUM_THREADS'] = os.environ['NSLOTS'] print "NSLOTS environment variable found; overriding any other thread settings and using N=%s threads" % os.environ['NSLOTS'] elif total_cores is None: print "OpenMP: Using %d threads" % num_threads os.environ['OMP_NUM_THREADS'] = str(num_threads) else: print "OpenMP: Using %d threads on a machine with %d detected CPUs" % (num_threads, total_cores) os.environ['OMP_NUM_THREADS'] = str(num_threads) # If no scripts and no commands were given, pretend -i was given. if not something_executed: interactive() if option.gui: topo.guimain.title(topo.sim.name) ## INTERACTIVE SESSION BEGINS HERE (i.e. can't have anything but ## some kind of cleanup code afterwards) if os.environ.get('PYTHONINSPECT'): print "Output path: %s" % param.normalize_path.prefix print BANNER # CBALERT: should probably allow a way for users to pass # things to IPython? Or at least set up some kind of # topographica ipython config file. Right now, a topo_parser # option has to be added for every ipython option we want to # support (e.g. see --pdb) if ipython_shell_interface == "IPython.Shell": # IPython 0.10 and earlier # Stop IPython namespace hack? # http://www.nabble.com/__main__-vs-__main__-td14606612.html __main__.__name__="__mynamespace__" ipython_args = ['-noconfirm_exit','-nobanner', '-pi1',CommandPrompt.get_format(), '-pi2',CommandPrompt2.get_format(), '-po',OutputPrompt.get_format()] if option.pdb: ipython_args.append('-pdb') ipshell = IPShell(ipython_args,user_ns=__main__.__dict__) ipshell.mainloop(sys_exit=1) elif ipython_shell_interface == "InteractiveShellEmbed": # IPython 0.11 and later config = Config() if ipython_prompt_interface == "PromptManager": config.PromptManager.in_template = CommandPrompt.get_format() config.PromptManager.in2_template = CommandPrompt2.get_format() config.PromptManager.out_template = OutputPrompt.get_format() else: config.InteractiveShell.prompt_in1 = CommandPrompt.get_format() config.InteractiveShell.prompt_in2 = CommandPrompt2.get_format() config.InteractiveShell.prompt_out = OutputPrompt.get_format() config.InteractiveShell.confirm_exit = False ipshell = IPShell(config=config,user_ns=__main__.__dict__, banner1="",exit_msg="") if option.pdb: ipshell.call_pdb = True ipshell() sys.exit()
def command(self): """Main command to create a new shell""" self.verbose = 3 if len(self.args) == 0: # Assume the .ini file is ./development.ini config_file = 'development.ini' if not os.path.isfile(config_file): raise BadCommand('%sError: CONFIG_FILE not found at: .%s%s\n' 'Please specify a CONFIG_FILE' % \ (self.parser.get_usage(), os.path.sep, config_file)) else: config_file = self.args[0] config_name = 'config:%s' % config_file here_dir = os.getcwd() locs = dict(__name__="pylons-admin") if not self.options.quiet: # Configure logging from the config file self.logging_file_config(config_file) # Load locals and populate with objects for use in shell sys.path.insert(0, here_dir) # Load the wsgi app first so that everything is initialized right wsgiapp = loadapp(config_name, relative_to=here_dir) test_app = paste.fixture.TestApp(wsgiapp) # Query the test app to setup the environment tresponse = test_app.get('/_test_vars') request_id = int(tresponse.body) # Disable restoration during test_app requests test_app.pre_request_hook = lambda self: \ paste.registry.restorer.restoration_end() test_app.post_request_hook = lambda self: \ paste.registry.restorer.restoration_begin(request_id) # Restore the state of the Pylons special objects # (StackedObjectProxies) paste.registry.restorer.restoration_begin(request_id) # Determine the package name from the pylons.config object pkg_name = pylons.config['pylons.package'] # Start the rest of our imports now that the app is loaded if is_minimal_template(pkg_name, True): model_module = None helpers_module = pkg_name + '.helpers' base_module = pkg_name + '.controllers' else: model_module = pkg_name + '.model' helpers_module = pkg_name + '.lib.helpers' base_module = pkg_name + '.lib.base' if model_module and can_import(model_module): locs['model'] = sys.modules[model_module] if can_import(helpers_module): locs['h'] = sys.modules[helpers_module] exec ('from pylons import app_globals, config, request, response, ' 'session, tmpl_context, url') in locs exec ('from pylons.controllers.util import abort, redirect') in locs exec 'from pylons.i18n import _, ungettext, N_' in locs locs.pop('__builtins__', None) # Import all objects from the base module __import__(base_module) base = sys.modules[base_module] base_public = [__name for __name in dir(base) if not \ __name.startswith('_') or __name == '_'] locs.update((name, getattr(base, name)) for name in base_public) locs.update(dict(wsgiapp=wsgiapp, app=test_app)) mapper = tresponse.config.get('routes.map') if mapper: locs['mapper'] = mapper banner = " All objects from %s are available\n" % base_module banner += " Additional Objects:\n" if mapper: banner += " %-10s - %s\n" % ('mapper', 'Routes mapper object') banner += " %-10s - %s\n" % ('wsgiapp', "This project's WSGI App instance") banner += " %-10s - %s\n" % ('app', 'paste.fixture wrapped around wsgiapp') try: if self.options.disable_ipython: raise ImportError() # try to use IPython if possible try: # ipython >= 0.11 from IPython.frontend.terminal.embed import InteractiveShellEmbed shell = InteractiveShellEmbed(banner2=banner) except ImportError: # ipython < 0.11 from IPython.Shell import IPShellEmbed shell = IPShellEmbed(argv=self.args) shell.set_banner(shell.IP.BANNER + '\n\n' + banner) try: shell(local_ns=locs, global_ns={}) finally: paste.registry.restorer.restoration_end() except ImportError: import code py_prefix = sys.platform.startswith('java') and 'J' or 'P' newbanner = "Pylons Interactive Shell\n%sython %s\n\n" % \ (py_prefix, sys.version) banner = newbanner + banner shell = code.InteractiveConsole(locals=locs) try: import readline except ImportError: pass try: shell.interact(banner) finally: paste.registry.restorer.restoration_end()
def ip(banner1='Dropping into IPython\n', **kw): "interactive IPython shell" shell = InteractiveShellEmbed.instance(banner1=banner1, **kw) shell(header='', stack_depth=2)