Ejemplo n.º 1
0
def console(**kwargs):
    """
    An REPL fully configured for experimentation.

    usage:
        blueberrypy console [options]

    options:
        -e ENVIRONMENT, --environment=ENVIRONMENT  apply the given config environment
        -C ENV_VAR_NAME, --env-var ENV_VAR_NAME    add the given config from environment variable name
                                                   [default: BLUEBERRYPY_CONFIG]
        --ipython                                  use IPython shell instead of Python one
        -h, --help                                 show this help message and exit

    """

    banner = """
*****************************************************************************
* If the configuration file you specified contains a [sqlalchemy_engine*]   *
* section, a default SQLAlchemy engine and session should have been created *
* for you automatically already.                                            *
*****************************************************************************
"""
    environment = kwargs.get("environment")
    config_dir = kwargs.get("config_dir")
    environment and cherrypy.config.update({"environment": environment})
    configuration = BlueberryPyConfiguration(
        config_dir=config_dir,
        environment=environment,
        env_var_name=kwargs.get('env_var'),
    )
    use_ipython = kwargs.get("ipython", False)
    package_name = shell.get_package_name(configuration)

    if use_ipython:
        try:
            from IPython.terminal.interactiveshell import TerminalInteractiveShell
        except ImportError as e:
            print(e)
            print("""Cannot import iPython. Did you install it?""")
            return
        try:
            app_package = import_module(package_name)
        except ImportError as e:
            print(e)
            app_package = None
        repl = TerminalInteractiveShell(
            user_ns=shell.get_user_namespace(configuration),
            user_module=app_package,
            display_completions='multicolumn',  # oldstyle is 'readlinelike'
            mouse_support=True,
            space_for_menu=10,  # reserve N lines for the completion menu
        )
        repl.show_banner(banner)
        repl.mainloop()
    else:
        try:
            import readline
        except ImportError as e:
            print(e)
        else:
            import rlcompleter
        sys.ps1 = "[%s]>>> " % package_name
        sys.ps2 = "[%s]... " % package_name

        ns = shell.get_user_namespace(configuration, include_pkg=True)
        repl = InteractiveConsole(locals=ns)
        repl.prompt = package_name
        repl.interact(banner)