示例#1
0
文件: paster.py 项目: jkrebs/pyramid
 def command(self, IPShell=_marker):
     if IPShell is _marker:
         try: #pragma no cover
             from IPython.Shell import IPShell
         except ImportError: #pragma no cover
             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 not None and not self.options.disable_ipython:
         try:
             shell = IPShell(argv=[], user_ns=shell_globals)
             shell.IP.BANNER = shell.IP.BANNER + '\n\n' + banner
             shell.mainloop()
         finally:
             closer()
     else:
         try:
             self.interact[0](banner, local=shell_globals)
         finally:
             closer()
示例#2
0
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)						
示例#3
0
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)
示例#4
0
 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()
示例#5
0
    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()
示例#6
0
 def ipython():
     try:
         from IPython import embed
         embed()
     except ImportError:
         from IPython.Shell import IPShell
         shell = IPShell(argv=[])
         shell.mainloop()
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)						
示例#8
0
 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()
示例#9
0
 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 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
示例#11
0
文件: shell.py 项目: 15580056814/hue
 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
示例#12
0
    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)
示例#13
0
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)
示例#14
0
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
示例#15
0
文件: celery.py 项目: llonchj/celery
 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()
示例#16
0
        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)
示例#17
0
    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)
示例#18
0
文件: shell.py 项目: gabrielx52/baph
 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
示例#19
0
 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
示例#20
0
 def ipython(self):
     try:
         # from IPython import embed
         # embed()
         import sys
         sys.argv=['ipython', 'console']
         from IPython.frontend.terminal.ipapp import launch_new_instance
         launch_new_instance()
     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
示例#21
0
文件: base.py 项目: rc/soops
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)
示例#22
0
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()
示例#23
0
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)
示例#24
0
文件: shell.py 项目: inducer/pudb
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)
示例#25
0
def interactive_mode(localvars=None, globalvars=None, IPOFF=False, argv=None):
    """A very simple function to embed an interactive interpreter into movpy."""
    # FIXME: could have the banner passed in as an optional argument
    #        plus maybe the IPython config file location
    if localvars is not None and globalvars is None:
        globalvars = localvars
    #
    try:
        from IPython.Shell import IPShell
    except ImportError:
        IPShell = None
    # NOTE: psyco and IPython are incompatible
    if (IPShell is None) or (IPOFF or psycofullon()):
        if localvars is None:
            # extract locals from the calling frame - taken from IPython
            localvars = sys._getframe(0).f_back.f_locals
        from code import InteractiveConsole
        con = InteractiveConsole(localvars)
        con.interact()
    else:
        banner = ('Movable Python\nIPython Interactive Shell. See the manual '
                  'for a list of features and tips.\nCtrl-D to exit.')
        # where to find the ipython config file
        if libdir:
            argv = ['-ipythondir', libdir] + (argv or [])
        try:
            ipshell = IPShell(argv, user_ns=localvars, user_global_ns=globalvars)
            ipshell.mainloop(banner=banner)
        except AttributeError, e:
            print e
            # if psyco is on, IPython will fail immediately with an AttributeError
            if localvars is None:
                # extract locals from the calling frame - taken from IPython
                localvars = sys._getframe(0).f_back.f_locals
            from code import InteractiveConsole
            con = InteractiveConsole(localvars)
            con.interact()
示例#26
0
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()
示例#27
0
    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()
示例#28
0
 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
示例#29
0
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
示例#30
0
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
示例#31
0
    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)
示例#32
0
文件: util.py 项目: spranesh/Redhawk
    def IPythonShell(namespace, banner):
        from IPython.Shell import IPShell

        ipshell = IPShell(user_ns=namespace)
        ipshell.mainloop(banner=banner)
示例#33
0
import os
示例#34
0
 def _ipython_pre_011(self):
     """Start IPython pre-0.11"""
     from IPython.Shell import IPShell
     shell = IPShell(argv=[])
     shell.mainloop()
示例#35
0
def interact_ipython():
    """Starts an IPython instance; halts the diesel app when finished."""
    IPShell(user_ns={'diesel': diesel}).mainloop()
    diesel.quickstop()
示例#36
0
 def run_ipython():
     imported_objects = self.get_imported_objects(options)
     shell = IPShell(argv=[], user_ns=imported_objects)
     shell.mainloop()
示例#37
0
def debug_shell(user_ns, user_global_ns):
	from IPython.Shell import IPShellEmbed,IPShell
	ipshell = IPShell(argv=[], user_ns=user_ns, user_global_ns=user_global_ns)
	#ipshell()
	ipshell.mainloop()
示例#38
0
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)
示例#39
0
文件: shell.py 项目: 01-/django
 def _ipython_pre_011(self):
     """Start IPython pre-0.11"""
     from IPython.Shell import IPShell
     shell = IPShell(argv=[])
     shell.mainloop()
 def run_ipython():
     imported_objects = import_objects(options, self.style)
     shell = IPShell(argv=[], user_ns=imported_objects)
     shell.mainloop()
示例#41
0
    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)
示例#42
0
    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
        config_uri = self.args[0]
        config_file = config_uri.split('#', 1)[0]
        self.logging_file_config(config_file)
        self.pshell_file_config(config_file)

        # bootstrap the environ
        env = self.bootstrap[0](config_uri)

        # remove the closer from the env
        closer = env.pop('closer')

        # setup help text for default environment
        env_help = dict(env)
        env_help['app'] = 'The WSGI application.'
        env_help['root'] = 'Root of the default resource tree.'
        env_help['registry'] = 'Active Pyramid registry.'
        env_help['request'] = 'Active request object.'
        env_help['root_factory'] = (
            'Default root factory used to create `root`.')

        # load the pshell section of the ini file
        env.update(self.loaded_objects)

        # eliminate duplicates from env, allowing custom vars to override
        for k in self.loaded_objects:
            if k in env_help:
                del env_help[k]

        # generate help text
        help = '\n'
        if env_help:
            help += 'Environment:'
            for var in sorted(env_help.keys()):
                help += '\n  %-12s %s' % (var, env_help[var])

        if self.object_help:
            help += '\n\nCustom Variables:'
            for var in sorted(self.object_help.keys()):
                help += '\n  %-12s %s' % (var, self.object_help[var])

        help += '\n'

        if (IPShell is None) or self.options.disable_ipython:
            cprt = 'Type "help" for more information.'
            banner = "Python %s on %s\n%s" % (sys.version, sys.platform, cprt)
            banner += '\n' + help
            try:
                self.interact[0](banner, local=env)
            finally:
                closer()
        else:
            try:
                shell = IPShell(argv=[], user_ns=env)
                shell.IP.BANNER = shell.IP.BANNER + help
                shell.mainloop()
            finally:
                closer()
示例#43
0
 def _ipython_010(self):  # pragma: no cover
     from IPython.Shell import IPShell
     IPShell(argv=[], user_ns=self.locals).mainloop()
示例#44
0
文件: paster.py 项目: deshank/pyramid
    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.'
        banner = "Python %s on %s\n%s" % (sys.version, sys.platform, cprt)
        app_spec = self.args[0]
        config_file = app_spec.split('#', 1)[0]
        self.logging_file_config(config_file)
        app = self.get_app(app_spec, loadapp=self.loadapp[0])

        # load default globals
        shell_globals = {
            'app': app,
        }
        default_variables = {'app': 'The WSGI Application'}
        if hasattr(app, 'registry'):
            root, closer = self.get_root(app)
            shell_globals.update({'root':root, 'registry':app.registry,
                                  'settings': app.registry.settings})
            default_variables.update({
                'root': 'The root of the default resource tree.',
                'registry': 'The Pyramid registry object.',
                'settings': 'The Pyramid settings object.',
            })
            warning = ''
        else:
            # warn the user that this isn't actually the Pyramid app
            warning = """\n
WARNING: You have loaded a generic WSGI application, therefore the "root",
"registry", and "settings" global variables are not available. To correct
this, run "pshell" again and specify the INI section containing your Pyramid
application.  For example, if your app is in the '[app:myapp]' config file
section, use 'development.ini#myapp' instead of 'development.ini' or
'development.ini#main'."""
            closer = lambda: None

        # load the pshell section of the ini file
        self.pshell_file_config(config_file)
        shell_globals.update(self.loaded_objects)

        # eliminate duplicates from default_variables
        for k in self.loaded_objects:
            if k in default_variables:
                del default_variables[k]

        # append the loaded variables
        if default_variables:
            banner += '\n\nDefault Variables:'
            for var, txt in default_variables.iteritems():
                banner += '\n  %-12s %s' % (var, txt)

        if self.object_help:
            banner += '\n\nCustom Variables:'
            for var in sorted(self.object_help.keys()):
                banner += '\n  %-12s %s' % (var, self.object_help[var])

        # append the warning
        banner += warning
        banner += '\n'

        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()
示例#45
0
    def handle(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.apps import apps
        # loaded_models = apps.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
        from django.utils.module_loading import import_module
        imported_objects = {'settings': settings, 'import_module': import_module}

        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 [import_module(appname) for appname in settings.INSTALLED_APPS]:
            app_models = apps.get_models(app_mod)
            if not app_models:
                continue
            app_name = app_mod.__name__
            if app_name in dont_load:
                continue

            model_labels = []
            for model in app_models:
                alias = model.__name__
                imported_objects[alias] = model
                model_labels.append(model.__name__)

            print self.style.SQL_COLTYPE("From '%s' autoload: %s" % (app_mod.__name__, ", ".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)
示例#46
0
 def launch_ipython():
     imported_objects = get_launch_args(**options)
     shell = IPShell(argv=[], user_ns=imported_objects)
     shell.mainloop()
示例#47
0
    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

示例#48
0
 def embed():
     shell = IPShell(argv=[])
     shell.mainloop()