Example #1
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()
Example #2
0
 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()
Example #3
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()
Example #4
0
 def ipython():
     try:
         from IPython import embed
         embed()
     except ImportError:
         from IPython.Shell import IPShell
         shell = IPShell(argv=[])
         shell.mainloop()
Example #5
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()
Example #6
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()
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)						
Example #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()
Example #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()
Example #10
0
 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):
     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
Example #12
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
Example #13
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
Example #14
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
Example #15
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()
Example #16
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()
Example #17
0
import os
Example #18
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()
Example #19
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.'
        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()
Example #20
0
 def launch_ipython():
     imported_objects = get_launch_args(**options)
     shell = IPShell(argv=[], user_ns=imported_objects)
     shell.mainloop()
 def run_ipython():
     imported_objects = import_objects(options, self.style)
     shell = IPShell(argv=[], user_ns=imported_objects)
     shell.mainloop()
Example #22
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)
Example #23
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()
Example #24
0
 def _ipython_pre_011(self):
     """Start IPython pre-0.11"""
     from IPython.Shell import IPShell
     shell = IPShell(argv=[])
     shell.mainloop()
Example #25
0
File: shell.py Project: 01-/django
 def _ipython_pre_011(self):
     """Start IPython pre-0.11"""
     from IPython.Shell import IPShell
     shell = IPShell(argv=[])
     shell.mainloop()
Example #26
0
    def IPythonShell(namespace, banner):
        from IPython.Shell import IPShell

        ipshell = IPShell(user_ns=namespace)
        ipshell.mainloop(banner=banner)
Example #27
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)
Example #28
0
 def embed():
     shell = IPShell(argv=[])
     shell.mainloop()
Example #29
0
 def run_ipython():
     imported_objects = self.get_imported_objects(options)
     shell = IPShell(argv=[], user_ns=imported_objects)
     shell.mainloop()
Example #30
0
 def embed():
     shell = IPShell(argv=[])
     shell.mainloop()