Skip to content

Instantly share code, notes, and snippets.

@leafsummer
Created July 2, 2019 02:36
Show Gist options
  • Save leafsummer/445dacf777cbb7012e018eed6f9ebedd to your computer and use it in GitHub Desktop.
Save leafsummer/445dacf777cbb7012e018eed6f9ebedd to your computer and use it in GitHub Desktop.
[interactive shell for click]
#!/usr/bin/env python
import click
@click.group()
def main():
"""
simple command manage tool
"""
pass
@main.command('shell', short_help='Runs a shell in the app context.')
@click.option('--plain', is_flag=True, default=False, help="to use plain Python, not IPython")
def shell_command(plain):
"""Runs an interactive Python shell in the context of a given
Flask application. The application will populate the default
namespace of this shell according to it's configuration.
This is useful for executing small snippets of management code
without having to manually configure the application.
"""
def python():
import code
app = webapp
banner = 'Python %s on %s\nApp: %s [%s]\nInstance: %s' % (
sys.version,
sys.platform,
app.import_name,
app.env,
app.instance_path,
)
ctx = {}
# Support the regular Python interpreter startup script if someone
# is using it.
startup = os.environ.get('PYTHONSTARTUP')
if startup and os.path.isfile(startup):
with open(startup, 'r') as f:
eval(compile(f.read(), startup, 'exec'), ctx)
ctx.update(app.make_shell_context())
code.interact(banner=banner, local=ctx)
def ipython():
from IPython import start_ipython
start_ipython(argv=[])
with webapp.app_context():
if plain:
python()
else:
try:
ipython()
except:
python()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment