Beispiel #1
0
    def __call__(self, context, args):
        # hijacked from pylons
        locs = {'ctx': context}
        banner_header = 'Melkman Interactive Shell\n'
        banner_footer = '\n\nYou may access the current context as "ctx"'
        try:
            # try to use IPython if possible
            from IPython.Shell import IPShellEmbed
            shell = IPShellEmbed(argv=sys.argv)
            banner = banner_header + shell.IP.BANNER + banner_footer
            shell.set_banner(banner)
            shell(local_ns=locs, global_ns={})
        except ImportError:
            import code
            pyver = 'Python %s' % sys.version
            banner = banner_header +  pyver + banner_footer

            shell = code.InteractiveConsole(locals=locs)
            try:
                import readline
            except ImportError:
                pass
            try:
                shell.interact(banner)
            finally:
                pass
Beispiel #2
0
    def __call__(self):
        class ShellCommands:
            pass

        cmds = ShellCommands()
        ShellCommands.__doc__ = "Commands:"
        for Command in sorted(plugins.get(COMMANDLINE_PLUGIN), key=attrgetter('command_name')):
            # help is skipped because it relates to the command line option
            # info for the commands.  The built-in python help should be 
            # used in the shell.
            if (not hasattr(Command, '__call__') or 
                Command == HelpCommand or 
                isinstance(self, Command)):
                continue
            
            shell_cmd = Command(self.config).__call__
            shell_cmd.__func__.__name__ = Command.command_name
            setattr(cmds, Command.command_name, shell_cmd)
            ShellCommands.__doc__ += "\n  "
            ShellCommands.__doc__ += Command.command_name.ljust(20)
            ShellCommands.__doc__ += Command.description
        ShellCommands.__doc__ += "\n\nType: help(cmds.<function>) for more info"
        
        locs = {'config': self.config, 'cmds': cmds }
        banner_header = 'RadarPost Interactive Shell\n'
        banner_footer = '\n\nYou may access the current config as "config"'
        banner_footer += '\nCLI commands are available as "cmds.<command>"'
        banner_footer += '\nType: help(cmds) for more info'
        try:
            # try to use IPython if possible
            from IPython.Shell import IPShellEmbed
            shell = IPShellEmbed(argv=sys.argv)
            banner = banner_header + shell.IP.BANNER + banner_footer
            shell.set_banner(banner)
            shell(local_ns=locs, global_ns={})
        except ImportError:
            import code
            pyver = 'Python %s' % sys.version
            banner = banner_header +  pyver + banner_footer

            shell = code.InteractiveConsole(locals=locs)
            try:
                import readline
            except ImportError:
                pass
            try:
                shell.interact(banner)
            finally:
                pass
Beispiel #3
0
 def command(self):
     
     # load the application
     config = self.load_configuration(self.args[0])
     setattr(config.app, 'reload', False)
     app = self.load_app(config)
     
     # prepare the locals
     locs = dict(__name__='pecan-admin')
     locs['wsgiapp'] = app
     locs['app'] = TestApp(app)
     
     # find the model for the app
     model = self.load_model(config)
     if model:
         locs['model'] = model
     
     # insert the pecan locals
     exec('from pecan import abort, conf, redirect, request, response') in locs
     
     # prepare the banner
     banner = '  The following objects are available:\n'
     banner += '  %-10s - This project\'s WSGI App instance\n' % 'wsgiapp'
     banner += '  %-10s - The current configuration\n' % 'conf'
     banner += '  %-10s - webtest.TestApp wrapped around wsgiapp\n' % 'app'
     if model:
         model_name = getattr(model, '__module__', getattr(model, '__name__', 'model'))
         banner += '  %-10s - Models from %s\n' % ('model', model_name)
     
     # launch the shell, using IPython if available
     try:
         from IPython.Shell import IPShellEmbed
         shell = IPShellEmbed(argv=self.args)
         shell.set_banner(shell.IP.BANNER + '\n\n' + banner)
         shell(local_ns=locs, global_ns={})
     except ImportError:
         import code
         py_prefix = sys.platform.startswith('java') and 'J' or 'P'
         shell_banner = 'Pecan Interactive Shell\n%sython %s\n\n' % \
             (py_prefix, sys.version)
         shell = code.InteractiveConsole(locals=locs)
         try:
             import readline
         except ImportError:
             pass
         shell.interact(shell_banner + banner)
    def _run_shell(self, base_module, locs, disable_ipython):
        banner = "  All objects from %s are available\n" % base_module
        banner += "  Additional Objects:\n"
        banner += "  %-10s -  %s\n" % ('wsgiapp',
                                       "This project's WSGI App instance")

        if 'app' in locs:
            banner += "  %-10s -  %s\n" % (
                'app', 'WebTest.TestApp wrapped around wsgiapp')

        try:
            if disable_ipython:
                raise ImportError()

            # try to use IPython if possible
            try:
                try:
                    # ipython >= 1.0
                    from IPython.terminal.embed import InteractiveShellEmbed
                except ImportError:
                    # ipython >= 0.11
                    from IPython.frontend.terminal.embed import InteractiveShellEmbed
                shell = InteractiveShellEmbed.instance(banner2=banner)
            except ImportError:
                # ipython < 0.11
                from IPython.Shell import IPShellEmbed
                shell = IPShellEmbed()
                shell.set_banner(shell.IP.BANNER + '\n\n' + banner)

            shell(local_ns=locs)
        except ImportError:
            import code
            py_prefix = sys.platform.startswith('java') and 'J' or 'P'
            newbanner = "TurboGears2 Interactive Shell\n%sython %s\n\n" % \
                        (py_prefix, sys.version)
            banner = newbanner + banner
            shell = code.InteractiveConsole(locals=locs)
            try:
                import readline
            except ImportError:
                pass

            shell.interact(banner)
Beispiel #5
0
def startshell(locals_={}, header='SiCDS Interactive Shell\n', footer=''):
    if not footer and locals_:
        footer = '\nThe following variables are available:\n  {0}'.format(
            ', '.join(locals_))
    try:
        # try to use IPython if possible
        from IPython.Shell import IPShellEmbed
        shell = IPShellEmbed(argv=sys.argv)
        banner = header + shell.IP.BANNER + footer
        shell.set_banner(banner)
        shell(local_ns=locals_, global_ns={})
    except ImportError:
        import code
        pyver = 'Python %s' % sys.version
        banner = header + pyver + footer
        shell = code.InteractiveConsole(locals=locals_)
        try:
            import readline
        except ImportError:
            pass
        try:
            shell.interact(banner)
        finally:
            pass
Beispiel #6
0
    def command(self):
        """Main command to create a new shell"""
        self.verbose = 3
        if len(self.args) == 0:
            # Assume the .ini file is ./development.ini
            config_file = 'development.ini'
            if not os.path.isfile(config_file):
                raise BadCommand('%sError: CONFIG_FILE not found at: .%s%s\n'
                                 'Please specify a CONFIG_FILE' % \
                                 (self.parser.get_usage(), os.path.sep,
                                  config_file))
        else:
            config_file = self.args[0]

        config_name = 'config:%s' % config_file
        here_dir = os.getcwd()

        if not self.options.quiet:
            # Configure logging from the config file
            self.logging_file_config(config_file)

        conf = appconfig(config_name, relative_to=here_dir)
        conf.update(dict(app_conf=conf.local_conf, global_conf=conf.global_conf))
        paste.deploy.config.CONFIG.push_thread_config(conf)

        # Load locals and populate with objects for use in shell
        sys.path.insert(0, here_dir)

        # Load the wsgi app first so that everything is initialized right
        wsgiapp = loadapp(config_name, relative_to=here_dir)
        test_app = paste.fixture.TestApp(wsgiapp)

        # Query the test app to setup the environment
        tresponse = test_app.get('/_test_vars')
        request_id = int(tresponse.body)

        # Disable restoration during test_app requests
        test_app.pre_request_hook = lambda self: paste.registry.restorer.restoration_end()
        test_app.post_request_hook = lambda self: paste.registry.restorer.restoration_begin(request_id)

        paste.registry.restorer.restoration_begin(request_id)

        locs = dict(__name__="webcore-admin", application=wsgiapp, test=test_app)

        exec 'import web' in locs
        exec 'from web.core import http, Controller, request, response, cache, session' in locs

        if len(self.args) == 2:
            execfile(self.args[1], {}, locs)
            return

        banner = "Welcome to the WebCore shell."

        try:
            if self.options.disable_ipython:
                raise ImportError()

            # try to use IPython if possible
            from IPython.Shell import IPShellEmbed

            shell = IPShellEmbed(argv=self.args)
            shell.set_banner(shell.IP.BANNER + '\n\n' + banner)

            try:
                shell(local_ns=locs, global_ns={})
            finally:
                paste.registry.restorer.restoration_end()
        except ImportError:
            import code
            py_prefix = sys.platform.startswith('java') and 'J' or 'P'
            newbanner = "WebCore Interactive Shell\n%sython %s\n\n" % (py_prefix, sys.version)
            banner = newbanner + banner
            shell = code.InteractiveConsole(locals=locs)

            try:
                import readline
            except ImportError:
                pass

            try:
                shell.interact(banner)
            finally:
                paste.registry.restorer.restoration_end()
Beispiel #7
0
    def command(self):
        """Main command to create a new shell"""
        self.verbose = 3
        if len(self.args) == 0:
            # Assume the .ini file is ./development.ini
            config_file = 'development.ini'
            if not os.path.isfile(config_file):
                raise BadCommand('%sError: CONFIG_FILE not found at: .%s%s\n'
                                 'Please specify a CONFIG_FILE' % \
                                 (self.parser.get_usage(), os.path.sep,
                                  config_file))
        else:
            config_file = self.args[0]

        config_name = 'config:%s' % config_file
        here_dir = os.getcwd()
        locs = dict(__name__="pylons-admin")

        # XXX: Note, initializing CONFIG here is Legacy support. pylons.config
        # will automatically be initialized and restored via the registry
        # restorer along with the other StackedObjectProxys
        # Load app config into paste.deploy to simulate request config
        # Setup the Paste CONFIG object, adding app_conf/global_conf for legacy
        # code
        conf = appconfig(config_name, relative_to=here_dir)
        conf.update(dict(app_conf=conf.local_conf,
                         global_conf=conf.global_conf))
        paste.deploy.config.CONFIG.push_thread_config(conf)

        # Load locals and populate with objects for use in shell
        sys.path.insert(0, here_dir)

        # Load the wsgi app first so that everything is initialized right
        wsgiapp = loadapp(config_name, relative_to=here_dir)
        test_app = paste.fixture.TestApp(wsgiapp)

        # Query the test app to setup the environment
        tresponse = test_app.get('/_test_vars')
        request_id = int(tresponse.body)

        # Disable restoration during test_app requests
        test_app.pre_request_hook = lambda self: \
            paste.registry.restorer.restoration_end()
        test_app.post_request_hook = lambda self: \
            paste.registry.restorer.restoration_begin(request_id)

        # Restore the state of the Pylons special objects
        # (StackedObjectProxies)
        paste.registry.restorer.restoration_begin(request_id)

        # Determine the package name from the .egg-info top_level.txt.
        egg_info = find_egg_info_dir(here_dir)
        f = open(os.path.join(egg_info, 'top_level.txt'))
        packages = [l.strip() for l in f.readlines()
                    if l.strip() and not l.strip().startswith('#')]
        f.close()

        # Start the rest of our imports now that the app is loaded
        found_base = False
        for pkg_name in packages:
            # Import all objects from the base module
            base_module = pkg_name + '.lib.base'
            found_base = can_import(base_module)
            if not found_base:
                # Minimal template
                base_module = pkg_name + '.controllers'
                found_base = can_import(base_module)

            if found_base:
                break

        if not found_base:
            raise ImportError("Could not import base module. Are you sure "
                              "this is a Pylons app?")

        base = sys.modules[base_module]
        base_public = [__name for __name in dir(base) if not \
                       __name.startswith('_') or __name == '_']
        for name in base_public:
            locs[name] = getattr(base, name)
        locs.update(dict(wsgiapp=wsgiapp, app=test_app))

        mapper = tresponse.config.get('routes.map')
        if mapper:
            locs['mapper'] = mapper

        banner = "  All objects from %s are available\n" % base_module
        banner += "  Additional Objects:\n"
        if mapper:
            banner += "  %-10s -  %s\n" % ('mapper', 'Routes mapper object')
        banner += "  %-10s -  %s\n" % ('wsgiapp',
            "This project's WSGI App instance")
        banner += "  %-10s -  %s\n" % ('app',
            'paste.fixture wrapped around wsgiapp')

        if not self.options.quiet:
            # Configure logging from the config file
            self.logging_file_config(config_file)
        
        try:
            if self.options.disable_ipython:
                raise ImportError()

            # try to use IPython if possible
            from IPython.Shell import IPShellEmbed

            shell = IPShellEmbed(argv=self.args)
            shell.set_banner(shell.IP.BANNER + '\n\n' + banner)
            try:
                shell(local_ns=locs, global_ns={})
            finally:
                paste.registry.restorer.restoration_end()
        except ImportError:
            import code
            newbanner = "Pylons Interactive Shell\nPython %s\n\n" % sys.version
            banner = newbanner + banner
            shell = code.InteractiveConsole(locals=locs)
            try:
                import readline
            except ImportError:
                pass
            try:
                shell.interact(banner)
            finally:
                paste.registry.restorer.restoration_end()
    def command(self):

        self.verbose = 3
        if len(self.args) == 0:
            config_file = "development.ini"
            if not os.path.isfile(config_file):
                raise BadCommand(
                    "%sError: CONFIG_FILE not found at: .%s%s\n"
                    "Please specify a CONFIG_FILE" % (self.parser.get_usage(), os.path.sep, config_file)
                )
        else:
            config_file = self.args[0]

        config_name = "config:%s" % config_file
        here_dir = os.getcwd()
        locs = dict(__name__="pylons-admin")

        if not self.options.quiet:
            self.logging_file_config(config_file)

        sys.path.insert(0, here_dir)

        wsgiapp = loadapp(config_name, relative_to=here_dir)
        test_app = paste.fixture.TestApp(wsgiapp)

        tresponse = test_app.get("/_test_vars")
        request_id = int(tresponse.body)

        test_app.pre_request_hook = lambda self: paste.registry.restorer.restoration_end()
        test_app.post_request_hook = lambda self: paste.registry.restorer.restoration_begin(request_id)

        paste.registry.restorer.restoration_begin(request_id)

        pkg_name = pylons.config["pylons.package"]

        if is_minimal_template(pkg_name, True):
            model_module = None
            helpers_module = pkg_name + ".helpers"
            base_module = pkg_name + ".controllers"
        else:
            model_module = pkg_name + ".model"
            helpers_module = pkg_name + ".lib.helpers"
            base_module = pkg_name + ".lib.base"

        if model_module and can_import(model_module):
            locs["model"] = sys.modules[model_module]

        if can_import(helpers_module):
            locs["h"] = sys.modules[helpers_module]

        exec ("from pylons import app_globals, config, request, response, " "session, tmpl_context, url") in locs
        exec ("from pylons.controllers.util import abort, redirect") in locs
        exec "from pylons.i18n import _, ungettext, N_" in locs
        locs.pop("__builtins__", None)

        __import__(base_module)

        base = sys.modules[base_module]
        base_public = [__name for __name in dir(base) if not __name.startswith("_") or __name == "_"]
        locs.update((name, getattr(base, name)) for name in base_public)
        locs.update(dict(wsgiapp=wsgiapp, app=test_app))

        mapper = tresponse.config.get("routes.map")
        if mapper:
            locs["mapper"] = mapper

        banner = "  All objects from %s are available\n" % base_module
        banner += "  Additional Objects:\n"
        if mapper:
            banner += "  %-10s -  %s\n" % ("mapper", "Routes mapper object")
        banner += "  %-10s -  %s\n" % ("wsgiapp", "This project's WSGI App instance")
        banner += "  %-10s -  %s\n" % ("app", "paste.fixture wrapped around wsgiapp")

        try:
            if self.options.disable_ipython:
                raise ImportError()

            from IPython.Shell import IPShellEmbed

            shell = IPShellEmbed(argv=self.args)
            shell.set_banner(shell.IP.BANNER + "\n\n" + banner)
            try:
                shell(local_ns=locs, global_ns={})
            finally:
                paste.registry.restorer.restoration_end()
        except ImportError:
            import code

            py_prefix = sys.platform.startswith("java") and "J" or "P"
            newbanner = "Pylons Interactive Shell\n%sython %s\n\n" % (py_prefix, sys.version)
            banner = newbanner + banner
            shell = code.InteractiveConsole(locals=locs)
            try:
                import readline
            except ImportError:
                pass
            try:
                shell.interact(banner)
            finally:
                paste.registry.restorer.restoration_end()
Beispiel #9
0
    def command(self):
        """Main command to create a new shell"""
        self.verbose = 3
        if len(self.args) == 0:
            # Assume the .ini file is ./development.ini
            config_file = 'development.ini'
            if not os.path.isfile(config_file):
                raise BadCommand('%sError: CONFIG_FILE not found at: .%s%s\n'
                                 'Please specify a CONFIG_FILE' %
                                 (self.parser.get_usage(), os.path.sep,
                                  config_file))
        else:
            config_file = self.args[0]

        config_name = 'config:%s' % config_file
        here_dir = os.getcwd()
        locs = dict(__name__="pylons-admin")

        if not self.options.quiet:
            # Configure logging from the config file
            self.logging_file_config(config_file)

        # XXX: Note, initializing CONFIG here is Legacy support. pylons.config
        # will automatically be initialized and restored via the registry
        # restorer along with the other StackedObjectProxys
        # Load app config into paste.deploy to simulate request config
        # Setup the Paste CONFIG object, adding app_conf/global_conf for legacy
        # code
        conf = appconfig(config_name, relative_to=here_dir)
        conf.update(dict(app_conf=conf.local_conf,
                         global_conf=conf.global_conf))
        paste.deploy.config.CONFIG.push_thread_config(conf)

        # Load locals and populate with objects for use in shell
        sys.path.insert(0, here_dir)

        # Load the wsgi app first so that everything is initialized right
        wsgiapp = loadapp(config_name, relative_to=here_dir)
        test_app = paste.fixture.TestApp(wsgiapp)

        # Query the test app to setup the environment
        tresponse = test_app.get('/_test_vars')
        request_id = int(tresponse.body)

        # Disable restoration during test_app requests
        test_app.pre_request_hook = lambda self: \
            paste.registry.restorer.restoration_end()
        test_app.post_request_hook = lambda self: \
            paste.registry.restorer.restoration_begin(request_id)

        # Restore the state of the Pylons special objects
        # (StackedObjectProxies)
        paste.registry.restorer.restoration_begin(request_id)

        # Determine the package name from the pylons.config object
        pkg_name = pylons.config['pylons.package']

        # Start the rest of our imports now that the app is loaded
        if is_minimal_template(pkg_name, True):
            model_module = None
            helpers_module = pkg_name + '.helpers'
            base_module = pkg_name + '.controllers'
        else:
            model_module = pkg_name + '.model'
            helpers_module = pkg_name + '.lib.helpers'
            base_module = pkg_name + '.lib.base'

        if model_module and can_import(model_module):
            locs['model'] = sys.modules[model_module]

        if can_import(helpers_module):
            locs['h'] = sys.modules[helpers_module]

        exec ('from pylons import app_globals, c, config, g, request, '
              'response, session, tmpl_context, url') in locs
        exec ('from pylons.controllers.util import abort, redirect_to') in locs
        exec 'from pylons.i18n import _, ungettext, N_' in locs
        exec 'from pylons.templating import render' in locs

        # Import all objects from the base module
        __import__(base_module)

        base = sys.modules[base_module]
        base_public = [__name for __name in dir(base) if not
                       __name.startswith('_') or __name == '_']
        for name in base_public:
            locs[name] = getattr(base, name)
        locs.update(dict(wsgiapp=wsgiapp, app=test_app))

        mapper = tresponse.config.get('routes.map')
        if mapper:
            locs['mapper'] = mapper

        banner = "  All objects from %s are available\n" % base_module
        banner += "  Additional Objects:\n"
        if mapper:
            banner += "  %-10s -  %s\n" % ('mapper', 'Routes mapper object')
        banner += "  %-10s -  %s\n" % ('wsgiapp',
                                       "This project's WSGI App instance")
        banner += "  %-10s -  %s\n" % ('app',
                                       'paste.fixture wrapped around wsgiapp')

        try:
            if self.options.disable_ipython:
                raise ImportError()

            # try to use IPython if possible
            from IPython.Shell import IPShellEmbed

            shell = IPShellEmbed(argv=self.args)
            shell.set_banner(shell.IP.BANNER + '\n\n' + banner)
            try:
                shell(local_ns=locs, global_ns={})
            finally:
                paste.registry.restorer.restoration_end()
        except ImportError:
            import code
            py_prefix = sys.platform.startswith('java') and 'J' or 'P'
            newbanner = "Pylons Interactive Shell\n%sython %s\n\n" % \
                (py_prefix, sys.version)
            banner = newbanner + banner
            shell = code.InteractiveConsole(locals=locs)
            try:
                import readline
            except ImportError:
                pass
            try:
                shell.interact(banner)
            finally:
                paste.registry.restorer.restoration_end()
Beispiel #10
0
    def command(self):
        """Main command to create a new shell"""
        self.verbose = 3
        if len(self.args) == 0:
            # Assume the .ini file is ./development.ini
            config_file = 'development.ini'
            if not os.path.isfile(config_file):
                raise BadCommand('%sError: CONFIG_FILE not found at: .%s%s\n'
                                 'Please specify a CONFIG_FILE' % \
                                 (self.parser.get_usage(), os.path.sep,
                                  config_file))
        else:
            config_file = self.args[0]

        config_name = 'config:%s' % config_file
        here_dir = os.getcwd()
        locs = dict(__name__="pylons-admin")

        # XXX: Note, initializing CONFIG here is Legacy support. pylons.config
        # will automatically be initialized and restored via the registry
        # restorer along with the other StackedObjectProxys
        # Load app config into paste.deploy to simulate request config
        # Setup the Paste CONFIG object, adding app_conf/global_conf for legacy
        # code
        conf = appconfig(config_name, relative_to=here_dir)
        conf.update(
            dict(app_conf=conf.local_conf, global_conf=conf.global_conf))
        paste.deploy.config.CONFIG.push_thread_config(conf)

        # Load locals and populate with objects for use in shell
        sys.path.insert(0, here_dir)

        # Load the wsgi app first so that everything is initialized right
        wsgiapp = loadapp(config_name, relative_to=here_dir)
        test_app = paste.fixture.TestApp(wsgiapp)

        # Query the test app to setup the environment
        tresponse = test_app.get('/_test_vars')
        request_id = int(tresponse.body)

        # Disable restoration during test_app requests
        test_app.pre_request_hook = lambda self: \
            paste.registry.restorer.restoration_end()
        test_app.post_request_hook = lambda self: \
            paste.registry.restorer.restoration_begin(request_id)

        # Restore the state of the Pylons special objects
        # (StackedObjectProxies)
        paste.registry.restorer.restoration_begin(request_id)

        # Determine the package name from the .egg-info top_level.txt.
        egg_info = find_egg_info_dir(here_dir)
        f = open(os.path.join(egg_info, 'top_level.txt'))
        packages = [
            l.strip() for l in f.readlines()
            if l.strip() and not l.strip().startswith('#')
        ]
        f.close()

        # Start the rest of our imports now that the app is loaded
        found_base = False
        for pkg_name in packages:
            # Import all objects from the base module
            base_module = pkg_name + '.lib.base'
            found_base = can_import(base_module)
            if not found_base:
                # Minimal template
                base_module = pkg_name + '.controllers'
                found_base = can_import(base_module)

            if found_base:
                break

        if not found_base:
            raise ImportError("Could not import base module. Are you sure "
                              "this is a Pylons app?")

        base = sys.modules[base_module]
        base_public = [__name for __name in dir(base) if not \
                       __name.startswith('_') or __name == '_']
        for name in base_public:
            locs[name] = getattr(base, name)
        locs.update(dict(wsgiapp=wsgiapp, app=test_app))

        mapper = tresponse.config.get('routes.map')
        if mapper:
            locs['mapper'] = mapper

        banner = "  All objects from %s are available\n" % base_module
        banner += "  Additional Objects:\n"
        if mapper:
            banner += "  %-10s -  %s\n" % ('mapper', 'Routes mapper object')
        banner += "  %-10s -  %s\n" % ('wsgiapp',
                                       "This project's WSGI App instance")
        banner += "  %-10s -  %s\n" % ('app',
                                       'paste.fixture wrapped around wsgiapp')

        if not self.options.quiet:
            # Configure logging from the config file
            self.logging_file_config(config_file)

        try:
            if self.options.disable_ipython:
                raise ImportError()

            # try to use IPython if possible
            from IPython.Shell import IPShellEmbed

            shell = IPShellEmbed(argv=self.args)
            shell.set_banner(shell.IP.BANNER + '\n\n' + banner)
            try:
                shell(local_ns=locs, global_ns={})
            finally:
                paste.registry.restorer.restoration_end()
        except ImportError:
            import code
            newbanner = "Pylons Interactive Shell\nPython %s\n\n" % sys.version
            banner = newbanner + banner
            shell = code.InteractiveConsole(locals=locs)
            try:
                import readline
            except ImportError:
                pass
            try:
                shell.interact(banner)
            finally:
                paste.registry.restorer.restoration_end()
Beispiel #11
0
    def command(self):
        """Main command to create a new shell"""
        self.verbose = 3
        if len(self.args) == 0:
            # Assume the .ini file is ./development.ini
            config_file = 'development.ini'
            if not os.path.isfile(config_file):
                raise BadCommand('%sError: CONFIG_FILE not found at: .%s%s\n'
                                 'Please specify a CONFIG_FILE' % \
                                 (self.parser.get_usage(), os.path.sep,
                                  config_file))
        else:
            config_file = self.args[0]

        config_name = 'config:%s' % config_file
        here_dir = os.getcwd()
        locs = dict(__name__="pylons-admin")

        if not self.options.quiet:
            # Configure logging from the config file
            self.logging_file_config(config_file)
        
        # Load locals and populate with objects for use in shell
        sys.path.insert(0, here_dir)

        # Load the wsgi app first so that everything is initialized right
        wsgiapp = loadapp(config_name, relative_to=here_dir)
        test_app = paste.fixture.TestApp(wsgiapp)

        # Query the test app to setup the environment
        tresponse = test_app.get('/_test_vars')
        request_id = int(tresponse.body)

        # Disable restoration during test_app requests
        test_app.pre_request_hook = lambda self: \
            paste.registry.restorer.restoration_end()
        test_app.post_request_hook = lambda self: \
            paste.registry.restorer.restoration_begin(request_id)

        # Restore the state of the Pylons special objects
        # (StackedObjectProxies)
        paste.registry.restorer.restoration_begin(request_id)
                
        # Determine the package name from the pylons.config object
        pkg_name = pylons.config['pylons.package']

        # Start the rest of our imports now that the app is loaded
        if is_minimal_template(pkg_name, True):
            model_module = None
            helpers_module = pkg_name + '.helpers'
            base_module = pkg_name + '.controllers'
        else:
            model_module = pkg_name + '.model'
            helpers_module = pkg_name + '.lib.helpers'
            base_module = pkg_name + '.lib.base'

        if model_module and can_import(model_module):
            locs['model'] = sys.modules[model_module]

        if can_import(helpers_module):
            locs['h'] = sys.modules[helpers_module]

        exec ('from pylons import app_globals, config, request, response, '
              'session, tmpl_context, url') in locs
        exec ('from pylons.controllers.util import abort, redirect') in locs
        exec 'from pylons.i18n import _, ungettext, N_' in locs
        locs.pop('__builtins__', None)
        
        # Import all objects from the base module
        __import__(base_module)

        base = sys.modules[base_module]
        base_public = [__name for __name in dir(base) if not \
                       __name.startswith('_') or __name == '_']
        locs.update((name, getattr(base, name)) for name in base_public)
        locs.update(dict(wsgiapp=wsgiapp, app=test_app))

        mapper = tresponse.config.get('routes.map')
        if mapper:
            locs['mapper'] = mapper

        banner = "  All objects from %s are available\n" % base_module
        banner += "  Additional Objects:\n"
        if mapper:
            banner += "  %-10s -  %s\n" % ('mapper', 'Routes mapper object')
        banner += "  %-10s -  %s\n" % ('wsgiapp',
            "This project's WSGI App instance")
        banner += "  %-10s -  %s\n" % ('app',
            'paste.fixture wrapped around wsgiapp')

        try:
            if self.options.disable_ipython:
                raise ImportError()

            # try to use IPython if possible
            from IPython.Shell import IPShellEmbed

            shell = IPShellEmbed(argv=self.args)
            shell.set_banner(shell.IP.BANNER + '\n\n' + banner)
            try:
                shell(local_ns=locs, global_ns={})
            finally:
                paste.registry.restorer.restoration_end()
        except ImportError:
            import code
            py_prefix = sys.platform.startswith('java') and 'J' or 'P'
            newbanner = "Pylons Interactive Shell\n%sython %s\n\n" % \
                (py_prefix, sys.version)
            banner = newbanner + banner
            shell = code.InteractiveConsole(locals=locs)
            try:
                import readline
            except ImportError:
                pass
            try:
                shell.interact(banner)
            finally:
                paste.registry.restorer.restoration_end()