def _ipython_pre_011(self): """Start IPython pre-0.11""" from IPython.Shell import IPShell user_ns = self.get_start_namespace() if user_ns: shell = IPShell(argv=[], user_ns=user_ns) else: shell = IPShell(argv=[]) shell.mainloop()
def _ipython_pre_011(): """Start IPython pre-0.11""" from IPython.Shell import IPShell # pylint: disable=import-error,no-name-in-module user_ns = get_start_namespace() if user_ns: ipy_shell = IPShell(argv=[], user_ns=user_ns) else: ipy_shell = IPShell(argv=[]) ipy_shell.mainloop()
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 invoke_ipython_shell(self): try: from IPython.frontend.terminal import embed embed.TerminalInteractiveShell(user_ns=self.locals).mainloop() except ImportError: # ipython < 0.11 from IPython.Shell import IPShell IPShell(argv=[], user_ns=self.locals).mainloop()
def failfast_or_pdb(step): has_traceback = step.why if not has_traceback: return sys.stdout.write(step.why.traceback + '\n') try: from IPython.core.debugger import Pdb pdb = Pdb() except ImportError: try: from IPython.Debugger import Pdb from IPython.Shell import IPShell IPShell(argv=['']) pdb = Pdb() except ImportError: import pdb matched, defined = step.pre_run(False) if matched: args = matched.groups() kwargs = matched.groupdict() pdb.runcall(defined.function, step, *args, **kwargs)
def command(self, IPShell=_marker): # IPShell passed to command method is for testing purposes if IPShell is _marker: # pragma: no cover try: from IPython.Shell import IPShell except ImportError: IPShell = None cprt = ('Type "help" for more information. "root" is the Pyramid app ' 'root object, "registry" is the Pyramid registry object.') banner = "Python %s on %s\n%s" % (sys.version, sys.platform, cprt) config_file, section_name = self.args self.logging_file_config(config_file) app = self.get_app(config_file, section_name, loadapp=self.loadapp[0]) root, closer = self.get_root(app) shell_globals = {'root': root, 'registry': app.registry} if (IPShell is None) or self.options.disable_ipython: try: self.interact[0](banner, local=shell_globals) finally: closer() else: try: shell = IPShell(argv=[], user_ns=shell_globals) shell.IP.BANNER = shell.IP.BANNER + '\n\n' + banner shell.mainloop() finally: closer()
def remote(args, context=None): """Starts a shell with the datastore as remote_api_stub. Args: args: arguments from the user context: locals that should be added to the shell """ if not context: context = {} app_id = args[0] host = args[1] if len(args) > 1 else None setupRemote(app_id, host) context['deepFetch'] = deepFetch try: from IPython.frontend.terminal.embed import TerminalInteractiveShell shell = TerminalInteractiveShell(user_ns=context) shell.mainloop() except ImportError: # IPython < 0.11 # Explicitly pass an empty list as arguments, because otherwise # IPython would use sys.argv from this script. try: from IPython.Shell import IPShell shell = IPShell(argv=[], user_ns=context) shell.mainloop() except ImportError: # IPython not found, use the vanilla interpreter shell code.interact('App Engine interactive console for %s' % (app_id, ), None, context)
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 debug_shell(user_ns, user_global_ns, execWrapper=None): ipshell = None if not ipshell: # old? doesn't work anymore. but probably has earlier, so leave it try: from IPython.Shell import IPShellEmbed, IPShell ipshell = IPShell(argv=[], user_ns=user_ns, user_global_ns=user_global_ns) ipshell = ipshell.mainloop except Exception: pass if not ipshell: try: import IPython class DummyMod(object): pass module = DummyMod() module.__dict__ = user_global_ns module.__name__ = "DummyMod" ipshell = IPython.frontend.terminal.embed.InteractiveShellEmbed( user_ns=user_ns, user_module=module) except Exception: pass else: if execWrapper: old = ipshell.run_code ipshell.run_code = lambda code: execWrapper(lambda: old(code)) if ipshell: ipshell() else: simple_debug_shell(user_global_ns, user_ns)
def handle_noargs(self, **options): # XXX: (Temporary) workaround for ticket #1796: force early loading of all # models from installed apps. from google.appengine._internal.django.db.models.loading import get_models loaded_models = get_models() use_plain = options.get('plain', False) try: if use_plain: # Don't bother loading IPython, because the user wants plain Python. raise ImportError try: from IPython.frontend.terminal.embed import TerminalInteractiveShell shell = TerminalInteractiveShell() shell.mainloop() except ImportError: # IPython < 0.11 # Explicitly pass an empty list as arguments, because otherwise # IPython would use sys.argv from this script. try: from IPython.Shell import IPShell shell = IPShell(argv=[]) shell.mainloop() except ImportError: # IPython not found at all, raise ImportError raise except ImportError: import code # Set up a dictionary to serve as the environment for the shell, so # that tab completion works on objects that are imported at runtime. # See ticket 5082. imported_objects = {} try: # Try activating rlcompleter, because it's handy. import readline except ImportError: pass else: # We don't have to wrap the following import in a 'try', because # we already know 'readline' was imported successfully. import rlcompleter readline.set_completer( rlcompleter.Completer(imported_objects).complete) readline.parse_and_bind("tab:complete") # We want to honor both $PYTHONSTARTUP and .pythonrc.py, so follow system # conventions and get $PYTHONSTARTUP first then import user. if not use_plain: pythonrc = os.environ.get("PYTHONSTARTUP") if pythonrc and os.path.isfile(pythonrc): try: exec( compile( open(pythonrc, "rb").read(), pythonrc, 'exec')) except NameError: pass # This will import .pythonrc.py as a side-effect import user code.interact(local=imported_objects)
def debug_shell(user_ns, user_global_ns): ipshell = None try: from IPython.Shell import IPShellEmbed,IPShell ipshell = IPShell(argv=[], user_ns=user_ns, user_global_ns=user_global_ns) except: pass if ipshell: #ipshell() ipshell.mainloop() else: simple_debug_shell(user_global_ns, user_ns)
def debug(frame=None, frames_back=1): """ Start debugger on line where it is called, roughly equivalent to:: import pdb; pdb.set_trace() First, this function tries to start an `IPython`-enabled debugger using the `IPython` API. When this fails, the plain old `pdb` is used instead. With IPython, one can say in what frame the debugger can stop. """ try: import IPython except ImportError: import pdb pdb.set_trace() else: old_excepthook = sys.excepthook 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 run_ipython(local): try: from IPython.frontend.terminal.embed import TerminalInteractiveShell shell = TerminalInteractiveShell(user_ns=local) shell.mainloop() except ImportError: # IPython < 0.11 # Explicitly pass an empty list as arguments, because otherwise # IPython would use sys.argv from this script. from IPython.Shell import IPShell shell = IPShell(argv=[], user_ns=local) shell.mainloop()
def run_ipython(): try: from IPython import embed embed(user_ns=imported_objects) 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 shell = IPShell(argv=[], user_ns=imported_objects) shell.mainloop()
def run_ipython_shell_v10(locals, globals, first_time): '''IPython shell from IPython version 0.10''' if first_time: banner = "Hit Ctrl-D to return to PuDB." else: banner = "" # avoid IPython's namespace litter ns = locals.copy() from IPython.Shell import IPShell IPShell(argv=[], user_ns=ns, user_global_ns=globals) \ .mainloop(banner=banner)
def run_ipython_shell_v10(globals, locals): """IPython shell from IPython version 0.10""" if SHELL_FIRST_TIME: banner = "Hit Ctrl-D to return to PuDB." SHELL_FIRST_TIME.pop() else: banner = "" # avoid IPython's namespace litter ns = locals.copy() from IPython.Shell import IPShell IPShell(argv=[], user_ns=ns, user_global_ns=globals) \ .mainloop(banner=banner)
def ipython(self): try: from IPython import embed embed() except ImportError: # IPython < 0.11 # Explicitly pass an empty list as arguments, because otherwise # IPython would use sys.argv from this script. try: from IPython.Shell import IPShell shell = IPShell(argv=[]) shell.mainloop() except ImportError: # IPython not found at all, raise ImportError raise
def ipython(self): #pragma nocoverage try: from IPython.frontend.terminal.embed import TerminalInteractiveShell shell = TerminalInteractiveShell() shell.mainloop() except ImportError: # IPython < 0.11 # Explicitly pass an empty list as arguments, because otherwise # IPython would use sys.argv from this script. try: from IPython.Shell import IPShell shell = IPShell(argv=[]) shell.mainloop() except ImportError: # IPython not found at all, raise ImportError raise
def ipython(self): try: from IPython.frontend.terminal.ipapp import TerminalIPythonApp app = TerminalIPythonApp.instance() app.initialize(argv=[]) app.start() except ImportError: # IPython < 0.11 # Explicitly pass an empty list as arguments, because otherwise # IPython would use sys.argv from this script. try: from IPython.Shell import IPShell shell = IPShell(argv=[]) shell.mainloop() except ImportError: # IPython not found at all, raise ImportError raise
def get_debugger(): """ Returns a debugger instance """ try: from IPython.core.debugger import Pdb pdb = Pdb() except ImportError: try: from IPython.Debugger import Pdb from IPython.Shell import IPShell IPShell(argv=[""]) pdb = Pdb() except ImportError: import pdb return pdb
def get_debugger(): """ Returns a debugger instance """ try: from IPython.core.debugger import Pdb pdb = Pdb() except ImportError: try: from IPython.Debugger import Pdb from IPython.Shell import IPShell IPShell(argv=[""]) pdb = Pdb() except ImportError: warnings.warn('pdb was selected as a debugger. If you want to use ipython as a debugger you have to "pip install radish-bdd[ipython-debugger]"') import pdb return pdb
class Command(NoArgsCommand): option_list = NoArgsCommand.option_list + ( make_option('--ipython', action='store_true', dest='ipython', help='Tells Django to use IPython, not BPython.'), make_option( '--plain', action='store_true', dest='plain', help='Tells Django to use plain Python, not BPython nor IPython.'), make_option('--no-pythonrc', action='store_true', dest='no_pythonrc', help='Tells Django to use plain Python, not IPython.'), make_option('--print-sql', action='store_true', default=False, help="Print SQL queries as they're executed"), make_option( '--dont-load', action='append', dest='dont_load', default=[], help= 'Ignore autoloading of some apps/models. Can be used several times.' ), ) help = "Like the 'shell' command but autoloads the models of all installed Django apps." requires_model_validation = True def handle_noargs(self, **options): # XXX: (Temporary) workaround for ticket #1796: force early loading of all # models from installed apps. (this is fixed by now, but leaving it here # for people using 0.96 or older trunk (pre [5919]) versions. from django.db.models.loading import get_models, get_apps loaded_models = get_models() use_ipython = options.get('ipython', False) use_plain = options.get('plain', False) use_pythonrc = not options.get('no_pythonrc', True) if options.get("print_sql", False): # Code from http://gist.github.com/118990 from django.db.backends import util try: import sqlparse except ImportError: sqlparse = None class PrintQueryWrapper(util.CursorDebugWrapper): def execute(self, sql, params=()): starttime = time.time() try: return self.cursor.execute(sql, params) finally: raw_sql = self.db.ops.last_executed_query( self.cursor, sql, params) execution_time = time.time() - starttime if sqlparse: print sqlparse.format(raw_sql, reindent=True) else: print raw_sql print print 'Execution time: %.6fs' % execution_time print util.CursorDebugWrapper = PrintQueryWrapper # Set up a dictionary to serve as the environment for the shell, so # that tab completion works on objects that are imported at runtime. # See ticket 5082. from django.conf import settings imported_objects = {'settings': settings} dont_load_cli = options.get( 'dont_load') # optparse will set this to [] if it doensnt exists dont_load_conf = getattr(settings, 'SHELL_PLUS_DONT_LOAD', []) dont_load = dont_load_cli + dont_load_conf model_aliases = getattr(settings, 'SHELL_PLUS_MODEL_ALIASES', {}) for app_mod in get_apps(): app_models = get_models(app_mod) if not app_models: continue app_name = app_mod.__name__.split('.')[-2] if app_name in dont_load: continue app_aliases = model_aliases.get(app_name, {}) model_labels = [] for model in app_models: try: imported_object = getattr( __import__(app_mod.__name__, {}, {}, model.__name__), model.__name__) model_name = model.__name__ if "%s.%s" % (app_name, model_name) in dont_load: continue alias = app_aliases.get(model_name, model_name) imported_objects[alias] = imported_object if model_name == alias: model_labels.append(model_name) else: model_labels.append("%s (as %s)" % (model_name, alias)) except AttributeError, e: print self.style.ERROR( "Failed to import '%s' from '%s' reason: %s" % (model.__name__, app_name, str(e))) continue print self.style.SQL_COLTYPE( "From '%s' autoload: %s" % (app_mod.__name__.split('.')[-2], ", ".join(model_labels))) try: if use_plain: # Don't bother loading B/IPython, because the user wants plain Python. raise ImportError try: if use_ipython: # User wants IPython raise ImportError from bpython import embed embed(imported_objects) except ImportError: try: from IPython import embed embed(user_ns=imported_objects) except ImportError: # IPython < 0.11 # Explicitly pass an empty list as arguments, because otherwise # IPython would use sys.argv from this script. try: from IPython.Shell import IPShell shell = IPShell(argv=[], user_ns=imported_objects) shell.mainloop() except ImportError: # IPython not found at all, raise ImportError raise except ImportError: # Using normal Python shell import code try: # Try activating rlcompleter, because it's handy. import readline except ImportError: pass else: # We don't have to wrap the following import in a 'try', because # we already know 'readline' was imported successfully. import rlcompleter readline.set_completer( rlcompleter.Completer(imported_objects).complete) readline.parse_and_bind("tab:complete") # We want to honor both $PYTHONSTARTUP and .pythonrc.py, so follow system # conventions and get $PYTHONSTARTUP first then import user. if use_pythonrc: pythonrc = os.environ.get("PYTHONSTARTUP") if pythonrc and os.path.isfile(pythonrc): try: execfile(pythonrc) except NameError: pass # This will import .pythonrc.py as a side-effect import user code.interact(local=imported_objects)
if 'nose' in sys.modules.keys(): def update_stdout(): # setup stdout to ensure output is available with nose io.stdout = sys.stdout = sys.__stdout__ else: def update_stdout(): pass else: from IPython.Debugger import Pdb, BdbQuit_excepthook 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 def_exec_lines = [] from IPython.Shell import Term if 'nose' in sys.modules.keys(): def update_stdout(): # setup stdout to ensure output is available with nose Term.cout = sys.stdout = sys.__stdout__ else: def update_stdout(): pass
def run_ipython(): imported_objects = self.get_imported_objects(options) shell = IPShell(argv=[], user_ns=imported_objects) shell.mainloop()
def launch_ipython(): imported_objects = get_launch_args(**options) shell = IPShell(argv=[], user_ns=imported_objects) shell.mainloop()
def _ipython_010(self): # pragma: no cover from IPython.Shell import IPShell IPShell(argv=[], user_ns=self.locals).mainloop()
def handle_noargs(self, **options): # XXX: (Temporary) workaround for ticket #1796: force early loading of all # models from installed apps. from django.db.models.loading import get_models, get_apps loaded_models = get_models() use_plain = options.get('plain', False) from django.conf import settings imported_objects = {'settings': settings} import_messages = [] for app_mod in get_apps(): app_models = get_models(app_mod) if not app_models: continue model_labels = [] for model in app_models: name = model.__name__ while name in imported_objects: name += '_' imported_objects[name] = model if model.__name__ == name: model_labels.append(name) else: model_labels.append("{} as {}".format( model.__name__, name)) import_messages.append( "Models from '%s': %s" "" % (app_mod.__name__.split('.')[-2], ", ".join(model_labels))) try: if use_plain: # Don't bother loading IPython, because the user wants plain # Python. raise ImportError try: from tempfile import mkstemp _, tmp_name = mkstemp(suffix='.py') tmp = open(tmp_name, 'w') try: tmp.write("\n".join( (('raise Warning, "%s"' if line.startswith("Failed") else 'print "%s"') % line for line in import_messages))) finally: tmp.close() try: from bpython import cli cli.main(args=['--interactive', tmp_name], locals_=imported_objects) finally: os.unlink(tmp_name) except ImportError: try: from IPython.frontend.terminal.embed import TerminalInteractiveShell shell = TerminalInteractiveShell() shell.mainloop() except ImportError: # IPython < 0.11 # Explicitly pass an empty list as arguments, because otherwise # IPython would use sys.argv from this script. try: from IPython.Shell import IPShell shell = IPShell(argv=[]) shell.mainloop() except ImportError: # IPython not found at all, raise ImportError raise except ImportError: import code # Set up a dictionary to serve as the environment for the shell, so # that tab completion works on objects that are imported at runtime. # See ticket 5082. for msg in import_messages: print msg try: # Try activating rlcompleter, because it's handy. import readline except ImportError: pass else: # We don't have to wrap the following import in a 'try', because # we already know 'readline' was imported successfully. import rlcompleter readline.set_completer( rlcompleter.Completer(imported_objects).complete) readline.parse_and_bind("tab:complete") # We want to honor both $PYTHONSTARTUP and .pythonrc.py, so follow # system conventions and get $PYTHONSTARTUP first then import user. if not use_plain: pythonrc = os.environ.get("PYTHONSTARTUP") if pythonrc and os.path.isfile(pythonrc): try: execfile(pythonrc) except NameError: pass # This will import .pythonrc.py as a side-effect import user code.interact(local=imported_objects)
def handle_noargs(self, **options): use_notebook = options.get('notebook', False) use_ipython = options.get('ipython', use_notebook) use_plain = options.get('plain', False) use_pythonrc = not options.get('no_pythonrc', True) if options.get("print_sql", False): # Code from http://gist.github.com/118990 from django.db.backends import util try: import sqlparse except ImportError: sqlparse = None class PrintQueryWrapper(util.CursorDebugWrapper): def execute(self, sql, params=()): starttime = time.time() try: return self.cursor.execute(sql, params) finally: raw_sql = self.db.ops.last_executed_query(self.cursor, sql, params) execution_time = time.time() - starttime if sqlparse: print sqlparse.format(raw_sql, reindent=True) else: print raw_sql print print 'Execution time: %.6fs [Database: %s]' % (execution_time, self.db.alias) print util.CursorDebugWrapper = PrintQueryWrapper # Set up a dictionary to serve as the environment for the shell, so # that tab completion works on objects that are imported at runtime. # See ticket 5082. try: if use_plain: # Don't bother loading B/IPython, because the user wants plain Python. raise ImportError try: if use_ipython: # User wants IPython raise ImportError from bpython import embed imported_objects = import_objects(options, self.style) embed(imported_objects) except ImportError: try: if use_notebook: from django.conf import settings from IPython.frontend.html.notebook import notebookapp app = notebookapp.NotebookApp.instance() ipython_arguments = getattr( settings, 'IPYTHON_ARGUMENTS', ['--ext', 'django_extensions.management.notebook_extension']) app.initialize(ipython_arguments) app.start() else: from IPython import embed imported_objects = import_objects(options, self.style) embed(user_ns=imported_objects) 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. try: from IPython.Shell import IPShell imported_objects = import_objects(options, self.style) shell = IPShell(argv=[], user_ns=imported_objects) shell.mainloop() except ImportError: # IPython not found at all, raise ImportError raise except ImportError: # Using normal Python shell import code imported_objects = import_objects(options, self.style) try: # Try activating rlcompleter, because it's handy. import readline except ImportError: pass else: # We don't have to wrap the following import in a 'try', because # we already know 'readline' was imported successfully. import rlcompleter readline.set_completer(rlcompleter.Completer(imported_objects).complete) readline.parse_and_bind("tab:complete") # We want to honor both $PYTHONSTARTUP and .pythonrc.py, so follow system # conventions and get $PYTHONSTARTUP first then import user. if use_pythonrc: pythonrc = os.environ.get("PYTHONSTARTUP") if pythonrc and os.path.isfile(pythonrc): try: execfile(pythonrc) except NameError: pass # This will import .pythonrc.py as a side-effect import user code.interact(local=imported_objects)
def interact_ipython(): """Starts an IPython instance; halts the diesel app when finished.""" IPShell(user_ns={'diesel': diesel}).mainloop() diesel.quickstop()
def _ipython_pre_011(self): """Start IPython pre-0.11""" from IPython.Shell import IPShell shell = IPShell(argv=[]) shell.mainloop()