def ipython(message=None, frame=None): """Launch into customized IPython with greedy autocompletion and no prompt to exit. If stdin is not tty, just issue warning message.""" import sys if os.isatty(sys.stdin.fileno()): config = Config({ 'InteractiveShell': {'confirm_exit': False, }, 'IPCompleter': {'greedy': True, } }) InteractiveShellEmbed.instance(config=config)(message, local_ns=frame.f_locals, global_ns=frame.f_globals) else: warn("==========> IPython cannot be launched if stdin is not a tty.\n\n")
def wrapper(namespace=namespace, banner=''): config = load_default_config() # Always use .instace() to ensure _instance propagation to all parents # this is needed for <TAB> completion works well for new imports shell = InteractiveShellEmbed.instance( banner1=banner, user_ns=namespace, config=config) shell()
def ipy(): """Run the IPython console in the context of the current frame. Useful for ad-hoc debugging.""" from IPython.terminal.embed import InteractiveShellEmbed from IPython import embed frame = sys._getframe(1) with stdio_to_tty(): shell = InteractiveShellEmbed.instance() shell(local_ns=frame.f_locals, global_ns=frame.f_globals)
def wrapper(namespace=namespace, banner=''): config = load_default_config() # Always use .instace() to ensure _instance propagation to all parents # this is needed for <TAB> completion works well for new imports # and clear the instance to always have the fresh env # on repeated breaks like with inspect_response() InteractiveShellEmbed.clear_instance() shell = InteractiveShellEmbed.instance( banner1=banner, user_ns=namespace, config=config) shell()
def _ipython(local, banner): from IPython.terminal.embed import InteractiveShellEmbed from IPython.terminal.ipapp import load_default_config InteractiveShellEmbed.clear_instance() shell = InteractiveShellEmbed.instance( banner1=banner, user_ns=local, config=load_default_config() ) shell()
def console(): """Starts an interactive IPython console""" import sys import builtins from IPython.terminal.embed import (load_default_config, InteractiveShell, InteractiveShellEmbed) header = 'Django debug console' config = load_default_config() config.InteractiveShellEmbed = config.TerminalInteractiveShell # save ps1/ps2 if defined ps1 = None ps2 = None try: ps1 = sys.ps1 ps2 = sys.ps2 except AttributeError: pass # save previous instance saved_shell_instance = InteractiveShell._instance if saved_shell_instance is not None: cls = type(saved_shell_instance) cls.clear_instance() # Starts shell retvalue = None def exit(value=None): nonlocal retvalue retvalue = value try: builtins.exit = exit shell = InteractiveShellEmbed.instance(config=config) shell(header=header, stack_depth=2, compile_flags=None) InteractiveShellEmbed.clear_instance() finally: pass # restore previous instance if saved_shell_instance is not None: cls = type(saved_shell_instance) cls.clear_instance() for subclass in cls._walk_mro(): subclass._instance = saved_shell_instance if ps1 is not None: sys.ps1 = ps1 sys.ps2 = ps2 return retvalue
def interact(self, **kwargs): from IPython.terminal.embed import InteractiveShellEmbed, load_default_config import sys config = kwargs.get('config') header = kwargs.pop('header', u'') compile_flags = kwargs.pop('compile_flags', None) if config is None: config = load_default_config() config.InteractiveShellEmbed = config.TerminalInteractiveShell kwargs['config'] = config frame = sys._getframe(1) shell = InteractiveShellEmbed.instance( _init_location_id='%s:%s' % ( frame.f_code.co_filename, frame.f_lineno), **kwargs) shell(header=header, stack_depth=2, compile_flags=compile_flags, _call_location_id='%s:%s' % (frame.f_code.co_filename, frame.f_lineno)) InteractiveShellEmbed.clear_instance()
def embed(pdb=False): from IPython.terminal.embed import InteractiveShellEmbed, load_default_config from IPython import Application, embed, get_ipython config = load_default_config() config.InteractiveShellEmbed = config.TerminalInteractiveShell config.InteractiveShellEmbed.pdb = pdb shell = InteractiveShellEmbed.instance(config=config) # my hook shell.set_hook('synchronize_with_editor', synchronize_with_editor) ### di, gu, gv etc... shell.safe_execfile('/home/ppalucki/workspace/djangoshellhelpers.py') ### start shell(stack_depth=2)
def _embed_ipython(self, load_extension=None, kwargs=None): from IPython.terminal.ipapp import load_default_config from IPython.terminal.embed import InteractiveShellEmbed kwargs = kwargs or {} config = kwargs.get('config') header = kwargs.pop('header', u'') compile_flags = kwargs.pop('compile_flags', None) if config is None: config = load_default_config() config.InteractiveShellEmbed = config.TerminalInteractiveShell kwargs['config'] = config kwargs.setdefault('display_banner', False) self._ishell = InteractiveShellEmbed.instance(**kwargs) if load_extension: load_extension(self._ishell) # Stack depth is 3 because we use self.embed first self._ishell(header=header, stack_depth=3, compile_flags=compile_flags) return self._ishell
def IPS(): # let the user know, where this shell is 'waking up' # construct frame list # this will be printed in the header frame_info_list = [] frame_list = [] frame = inspect.currentframe() while not frame == None: frame_list.append(frame) info = inspect.getframeinfo(frame) frame_info_list.append(info) frame = frame.f_back frame_info_list.reverse() frame_list.reverse() frame_info_str_list = [format_frameinfo(fi) for fi in frame_info_list] custom_header1 = "----- frame list -----\n\n" frame_info_str = "\n--\n".join(frame_info_str_list[:-1]) custom_header2 = "\n----- end of frame list -----\n" custom_header = "{0}{1}{2}".format(custom_header1, frame_info_str, custom_header2) # prevent IPython shell to be launched in IP-Notebook test_str = str(frame_info_list[0]) + str(frame_info_list[1]) # print test_str if "IPython" in test_str and "zmq" in test_str: print "\n- Not entering IPython embedded shell -\n" return # copied (and modified) from IPython/terminal/embed.py config = load_default_config() config.InteractiveShellEmbed = config.TerminalInteractiveShell # these two lines prevent problems in related to the initialization # of ultratb.FormattedTB below InteractiveShellEmbed.clear_instance() InteractiveShellEmbed._instance = None shell = InteractiveShellEmbed.instance() shell(header=custom_header, stack_depth=2)
def ipython(user_ns=None): os.environ['IPYTHONDIR'] = ipydir try: from IPython.terminal.embed import InteractiveShellEmbed from traitlets.config.loader import Config from IPython.terminal.prompts import Prompts, Token except ImportError: return simple_repl(user_ns=user_ns) class CustomPrompt(Prompts): def in_prompt_tokens(self, cli=None): return [ (Token.Prompt, 'calibre['), (Token.PromptNum, get_version()), (Token.Prompt, ']> '), ] def out_prompt_tokens(self): return [] defns = {'os':os, 're':re, 'sys':sys} defns.update(user_ns or {}) c = Config() user_conf = os.path.expanduser('~/.ipython/profile_default/ipython_config.py') if os.path.exists(user_conf): execfile(user_conf, {'get_config': lambda: c}) c.TerminalInteractiveShell.prompts_class = CustomPrompt c.InteractiveShellApp.exec_lines = [ 'from __future__ import division, absolute_import, unicode_literals, print_function', ] c.TerminalInteractiveShell.confirm_exit = False c.TerminalInteractiveShell.banner1 = BANNER c.BaseIPythonApplication.ipython_dir = ipydir c.InteractiveShell.separate_in = '' c.InteractiveShell.separate_out = '' c.InteractiveShell.separate_out2 = '' ipshell = InteractiveShellEmbed.instance(config=c, user_ns=user_ns) ipshell()
def embed2(**kwargs): """ Modified from IPython.terminal.embed.embed so I can mess with stack_depth """ config = kwargs.get('config') header = kwargs.pop('header', u'') stack_depth = kwargs.pop('stack_depth', 2) compile_flags = kwargs.pop('compile_flags', None) import IPython from IPython.core.interactiveshell import InteractiveShell from IPython.terminal.embed import InteractiveShellEmbed if config is None: config = IPython.terminal.ipapp.load_default_config() config.InteractiveShellEmbed = config.TerminalInteractiveShell kwargs['config'] = config #save ps1/ps2 if defined ps1 = None ps2 = None try: ps1 = sys.ps1 ps2 = sys.ps2 except AttributeError: pass #save previous instance saved_shell_instance = InteractiveShell._instance if saved_shell_instance is not None: cls = type(saved_shell_instance) cls.clear_instance() shell = InteractiveShellEmbed.instance(**kwargs) shell(header=header, stack_depth=stack_depth, compile_flags=compile_flags) InteractiveShellEmbed.clear_instance() #restore previous instance if saved_shell_instance is not None: cls = type(saved_shell_instance) cls.clear_instance() for subclass in cls._walk_mro(): subclass._instance = saved_shell_instance if ps1 is not None: sys.ps1 = ps1 sys.ps2 = ps2
def ipython(user_ns=None): ipydir = os.path.join(cache_dir, 'ipython') os.environ['IPYTHONDIR'] = ipydir BANNER = ('Welcome to the interactive vise shell!\n') from IPython.terminal.embed import InteractiveShellEmbed from traitlets.config.loader import Config from IPython.terminal.prompts import Prompts, Token class CustomPrompt(Prompts): def in_prompt_tokens(self, cli=None): return [ (Token.Prompt, 'vise['), (Token.PromptNum, str_version), (Token.Prompt, ']> '), ] def out_prompt_tokens(self): return [] defns = {'os': os, 're': re, 'sys': sys} defns.update(user_ns or {}) c = Config() c.TerminalInteractiveShell.prompts_class = CustomPrompt c.InteractiveShellApp.exec_lines = [ 'from __future__ import division, absolute_import, unicode_literals, print_function', ] c.TerminalInteractiveShell.confirm_exit = False c.TerminalInteractiveShell.banner1 = BANNER c.BaseIPythonApplication.ipython_dir = ipydir c.InteractiveShell.separate_in = '' c.InteractiveShell.separate_out = '' c.InteractiveShell.separate_out2 = '' ipshell = InteractiveShellEmbed.instance(config=c, user_ns=user_ns) ipshell()
def ip(banner1='', **kw): shell = InteractiveShellEmbed.instance(banner1=banner1, **kw) shell(header='', stack_depth=2)
if 1: # initialize QApplication from PyQt4 import QtGui if woo.runtime.ipython_version()==10: wooQApp=QtGui.QApplication(sys.argv) elif useQtConsole: from IPython.frontend.qt.console.qtconsoleapp import IPythonQtConsoleApp wooQApp=IPythonQtConsoleApp() wooQApp.initialize() else: # create an instance of InteractiveShell before the inputhook is created # see http://stackoverflow.com/questions/9872517/how-to-embed-ipython-0-12-so-that-it-inherits-namespace-of-the-caller for details # fixes http://gpu.doxos.eu/trac/ticket/40 try: from IPython.terminal.embed import InteractiveShellEmbed # IPython>=1.0 except ImportError: from IPython.frontend.terminal.embed import InteractiveShellEmbed # IPython<1.0 from IPython.config.configurable import MultipleInstanceError try: ipshell=InteractiveShellEmbed.instance() except MultipleInstanceError: print 'Already running inside ipython, not embedding new instance.' # keep the qapp object referenced, otherwise 0.11 will die with "QWidget: Must construct QApplication before a QPaintDevice # see also http://ipython.org/ipython-doc/dev/interactive/qtconsole.html#qt-and-the-qtconsole import IPython.lib.inputhook #guisupport wooQApp=IPython.lib.inputhook.enable_gui(gui='qt4') #from IPython.lib.guisupport import start_event_loop_qt4 #start_event_loop_qt4(wooQApp) #try: # wooQApp.setStyleSheet(open(woo.config.resourceDir+'/qmc2-black-0.10.qss').read()) #except IOError: pass # stylesheet not readable or whatever if sys.platform=='win32': # don't use ugly windows theme, try something else
parser.add_argument('-m', '--swarm-mappings', dest='swarm_mappings', metavar='SWARM_MAPPINGS', nargs='+', default=SWARM_MAPPINGS, help='Use files SWARM_MAPPINGS to determine the SWARM input to IF mapping (default="{0}")'.format(SWARM_MAPPINGS)) args = parser.parse_args() # Setup logging logging.basicConfig() logging.getLogger('katcp').setLevel(logging.CRITICAL) logging.getLogger('').setLevel(logging.DEBUG if args.verbose else logging.INFO) # Set up SWARM swarm = Swarm(map_filenames=args.swarm_mappings) # Commands added by Taco: def takeNoiseData(): print "Enabling noise source - type takeSkyData() to undo this" swarm.members_do(lambda i,m: m.dewalsh(False,False)) swarm.send_katcp_cmd("sma-astro-fstop-set","7.85","-12.15","-2.71359","0","0") def takeSkyData(): swarm.set_walsh_patterns() swarm.send_katcp_cmd("sma-astro-fstop-set","7.85","-12.15","-2.71359","1","1") swarm.fringe_stopping(True) # End of commands added by Taco # Start the IPython embedded shell ipshell = InteractiveShellEmbed.instance(config=cfg) swarm_shell_magics = magics.SwarmShellMagics(ipshell, swarm) ipshell.register_magics(swarm_shell_magics) ipshell()
import asyncio import concurrent.futures from functools import partial from threading import Thread from IPython.terminal.embed import InteractiveShellEmbed _shell = InteractiveShellEmbed.instance() def _await(coro, context): f = concurrent.futures.Future() async def wrap(coro): try: result = await coro except Exception as e: f.set_exception(e) else: f.set_result(result) context.loop.call_soon_threadsafe(context.loop.create_task, wrap(coro)) return f.result() def shell(run): _f = concurrent.futures.Future() def _thread(): context = _f.result() await = partial(_await, context=context)
def IPS(copy_namespaces=True, overwrite_globals=False): """Starts IPython embedded shell. This is similar to IPython.embed() but with some additional features: 1. Print a list of the calling frames before entering the prompt 2. (optionally) copy local name space to global one to prevent certain IPython bug. 3. while doing so optinally overwrite names in the global namespace """ # let the user know, where this shell is 'waking up' # construct frame list # this will be printed in the header frame_info_list = [] frame_list = [] frame = inspect.currentframe() while frame is not None: frame_list.append(frame) info = inspect.getframeinfo(frame) frame_info_list.append(info) frame = frame.f_back frame_info_list.reverse() frame_list.reverse() frame_info_str_list = [format_frameinfo(fi) for fi in frame_info_list] custom_header1 = "----- frame list -----\n\n" frame_info_str = "\n--\n".join(frame_info_str_list[:-1]) custom_header2 = "\n----- end of frame list -----\n" custom_header = "{0}{1}{2}".format(custom_header1, frame_info_str, custom_header2) # prevent IPython shell to be launched in IP-Notebook test_str = str(frame_info_list[0]) + str(frame_info_list[1]) if 'IPython' in test_str and 'zmq' in test_str: print("\n- Not entering IPython embedded shell -\n") return # copied (and modified) from IPython/terminal/embed.py config = load_default_config() config.InteractiveShellEmbed = config.TerminalInteractiveShell # these two lines prevent problems related to the initialization # of ultratb.FormattedTB below InteractiveShellEmbed.clear_instance() InteractiveShellEmbed._instance = None shell = InteractiveShellEmbed.instance() # achieve that custom macros are loade in interactive shell shell.magic('load_ext storemagic') if config.StoreMagics.autorestore: shell.magic('store -r') ar_keys = [k.split("/")[-1] for k in shell.db.keys() if k.startswith("autorestore/")] else: ar_keys = [] # adapt the namespaces to prevent missing names inside the shell # see: https://github.com/ipython/ipython/issues/62 # https://github.com/ipython/ipython/issues/10695 if copy_namespaces and len(frame_list) >= 2: # callers_frame to IPS() # note that frame_list and frame_info_list were reversed above f1 = frame_list[-2] lns = f1.f_locals gns = f1.f_globals l_keys = set(lns) g_keys = set(gns) u_keys = shell.user_ns.keys() # those keys which are in local ns but not in global safe_keys = l_keys - g_keys unsafe_keys = l_keys.intersection(g_keys) assert safe_keys.union(unsafe_keys) == l_keys gns.update({k:lns[k] for k in safe_keys}) if unsafe_keys and not overwrite_globals: custom_header += "following local keys have " \ "not been copied:\n{}\n".format(unsafe_keys) if unsafe_keys and overwrite_globals: gns.update({k:lns[k] for k in unsafe_keys}) custom_header += "following global keys have " \ "been overwritten:\n{}\n".format(unsafe_keys) # now update the gns with stuff from the user_ns (if it will not overwrite anything) # this could be implemented cleaner for k in ar_keys: if k not in gns: gns[k] = shell.user_ns[k] else: print("omitting key from user_namespace:", k) dummy_module = DummyMod() dummy_module.__dict__ = gns else: # unexpected few frames or no copying desired: lns = None dummy_module = None # now execute the shell shell(header=custom_header, stack_depth=2, local_ns=lns, module=dummy_module) custom_excepthook = getattr(sys, 'custom_excepthook', None) if custom_excepthook is not None: assert callable(custom_excepthook) sys.excepthook = custom_excepthook
def embed2(**kwargs): """Call this to embed IPython at the current point in your program. The first invocation of this will create an :class:`InteractiveShellEmbed` instance and then call it. Consecutive calls just call the already created instance. If you don't want the kernel to initialize the namespace from the scope of the surrounding function, and/or you want to load full IPython configuration, you probably want `IPython.start_ipython()` instead. Here is a simple example:: from IPython import embed a = 10 b = 20 embed(header='First time') c = 30 d = 40 embed() Full customization can be done by passing a :class:`Config` in as the config argument. """ ix() # MYCHANGE config = kwargs.get("config") header = kwargs.pop("header", "") compile_flags = kwargs.pop("compile_flags", None) if config is None: config = load_default_config() config.InteractiveShellEmbed = config.TerminalInteractiveShell kwargs["config"] = config using = kwargs.get("using", "asyncio") # MYCHANGE if using: kwargs["config"].update({ "TerminalInteractiveShell": { "loop_runner": using, "colors": "NoColor", "autoawait": using != "sync", } }) # save ps1/ps2 if defined ps1 = None ps2 = None try: ps1 = sys.ps1 ps2 = sys.ps2 except AttributeError: pass # save previous instance saved_shell_instance = InteractiveShell._instance if saved_shell_instance is not None: cls = type(saved_shell_instance) cls.clear_instance() frame = sys._getframe(1) shell = InteractiveShellEmbed.instance( _init_location_id="%s:%s" % (frame.f_code.co_filename, frame.f_lineno), **kwargs) shell( header=header, stack_depth=2, compile_flags=compile_flags, _call_location_id="%s:%s" % (frame.f_code.co_filename, frame.f_lineno), ) InteractiveShellEmbed.clear_instance() # restore previous instance if saved_shell_instance is not None: cls = type(saved_shell_instance) cls.clear_instance() for subclass in cls._walk_mro(): subclass._instance = saved_shell_instance if ps1 is not None: sys.ps1 = ps1 sys.ps2 = ps2