def BPy_Shell(): """ TODO: write the helpers you mentioned in SHELL.md. """ try: banner = """ ~ MyLatitude interactive shell. Scope: * app - Flask instance * db - SQLAlchemy instance * models - SQLAlchemy model definitions * db_create() - Create the database & all tables. * db_destroy() - Destroys the database & all tables. """ import bpython scope = {} scope['app'] = app scope['db'] = db scope['models'] = models scope['db_create'] = models.METHODS.Create scope['db_drop'] = models.METHODS.Drop bpython.embed(locals_=scope, banner=banner) except Exception, e: abort(msg="Encountered an exception while loading the bpython shell. \ \n -- \n%s" % e.message)
def key_func(x): # For some year like 2011 the year is 2 digits so the date format #should ne %m%d%y but for others like 2015 it should be %m%d%Y try: #date = "" if '(' in x: date_ = x.split('D_')[-1].split('(')[0].strip() else: date_ = x.split('D_')[-1].split('.')[0].strip() mdy = date_.split('_') m = mdy[0] d = mdy[1] y = mdy[2] if len(m) == 1: m = '0' + m if len(d) == 1: d = '0' + d date_ = m + d + y if len(date_) == 6: #the format that has 2 digits for year return datetime.datetime.strptime(date_, '%m%d%y') else: return datetime.datetime.strptime(date_, '%m%d%Y') except: print(x) import bpython bpython.embed(locals()) exit()
def run(self, no_ipython, no_bpython): """ Runs the shell. If no_bpython is False or use_bpython is True, then a BPython shell is run (if installed). Else, if no_ipython is False or use_python is True then a IPython shell is run (if installed). """ context = self.get_context() if not no_bpython: # Try BPython try: from bpython import embed embed(banner=self.banner, locals_=self.get_context()) return except ImportError: # Try IPython if not no_ipython: try: import IPython try: sh = IPython.Shell.IPShellEmbed(banner=self.banner) except AttributeError: sh = IPython.frontend.terminal.embed.InteractiveShellEmbed(banner1=self.banner) sh(global_ns=dict(), local_ns=context) return except ImportError: pass # Use basic python shell code.interact(self.banner, local=context)
def run(self, args): # bpython does it's own history thing. # Make sure it doesn't damage ours. have_line_edit = self.debugger.intf[-1].input.line_edit if have_line_edit: try: self.proc.write_history_file() except IOError: pass pass banner_tmpl='''trepan2 python shell%s Use dbgr(*string*) to issue debugger command: *string*''' debug = len(args) > 1 and args[1] == '-d' if debug: banner_tmpl += ("\nVariable 'debugger' contains a trepan" + "debugger object.") pass my_locals = {} my_globals = None if self.proc.curframe: my_globals = self.proc.curframe.f_globals if self.proc.curframe.f_locals: my_locals = self.proc.curframe.f_locals pass pass # Give python and the user a way to get access to the debugger. if debug: my_locals['debugger'] = self.debugger my_locals['dbgr'] = self.dbgr if len(my_locals): banner=(banner_tmpl % ' with locals') else: banner=(banner_tmpl % '') pass sys.ps1 = 'trepan2 >>> ' try: import bpython bpython.embed(my_locals, ['-i'], banner=banner) except ImportError: return # restore completion and our history if we can do so. if hasattr(self.proc.intf[-1], 'complete'): try: from readline import set_completer, parse_and_bind parse_and_bind("tab: complete") set_completer(self.proc.intf[-1].complete) except ImportError: pass pass if have_line_edit: self.proc.read_history_file() pass return
def bpython(_): try: import bpython except ImportError: raise ImportError("BPython must be installed") bpython.embed()
def run_shell(self, no_ipython, no_bpython, quiet): # based on the flask-script Shell.run() method context = self.get_context() if not no_bpython: try: from bpython import embed embed(banner=self.banner, locals_=context) return except ImportError: pass if not no_ipython: try: from IPython.terminal.ipapp import TerminalIPythonApp ipython_app = TerminalIPythonApp.instance(user_ns=context, display_banner=not quiet) ipython_app.initialize(argv=[]) ipython_app.shell.show_banner(self.banner) ipython_app.start() return except ImportError: pass # Use basic python shell import code code.interact(self.banner, local=context)
def bpython(args): from gridtest.main.test import GridRunner, GridTest import bpython runner = get_runner(args) print_runner(runner, args.input) bpython.embed(locals_={"runner": runner, "testfile": args.input})
def load_mask(self, image_id): """Generate instance masks for shapes of the given image ID. """ info = self.image_info[image_id] #print("info: ", info) shapes = info['images'] count = len(shapes) mask = np.zeros([info['height'], info['width'], count], dtype=np.uint8) for i, (shape, dims) in enumerate(info['images']): mask[:, :, i:i + 1] = self.draw_shape(mask[:, :, i:i + 1].copy(), shape, dims, 1) mask_temp = mask.copy() # Handle occlusions occlusion = np.logical_not(mask[:, :, -1]).astype(np.uint8) for i in range(count - 2, -1, -1): if (mask[:, :, i] * occlusion).any(): mask[:, :, i] = mask[:, :, i] * occlusion occlusion = np.logical_and(occlusion, np.logical_not(mask[:, :, i])) # Map class names to class IDs. class_ids = np.array([self.class_names.index(s[0]) for s in shapes]) if mask[:, :, 0].sum() == 0: import bpython bpython.embed(locals()) if mask.sum() == 0: print("The mask was all zeros") #print("output of the load_mask:", mask, class_ids.astype(np.int32)) return mask, class_ids.astype(np.int32)
def repl(type): """ Read Eval Print Loop for the current LWC. TYPE can be one of: ptpy, ipy, bpy, cpy. ptpy is the ptpython enhanced curses repl. ipy is the ptpython repl in ipython mode. bpy is the bpython enhanced curses repl. cpy is the vanilla cpython repl. """ if type == 'ptpy': import ptpython.repl ptpython.repl.embed(globals(), locals()) if type == 'ipy': import ptpython.ipython ptpython.ipython.embed() elif type == 'bpy': import bpython bpython.embed() elif type == 'cpy': import code code.interact()
def main(): kwargs = {dest: os.environ.get(env) for dest, env in ENVIRONMENT_VARIABLES.items()} parser = argparse.ArgumentParser() cloud_config = os_client_config.OpenStackConfig() cloud_config.register_argparse_arguments(parser, sys.argv) for opt in parser._actions: if opt.dest in ENVIRONMENT_VARIABLES: opt.metavar = ENVIRONMENT_VARIABLES[opt.dest] parser.set_defaults(timeout=None, **kwargs) parser.add_argument('--version', help='Print version and exit', action='store_true') parser.add_argument('--verbose', help='Verbose output', action='store_true') options = parser.parse_args() if options.version: print(pbr.version.VersionInfo('yakumo')) sys.exit(0) c = yakumo.Client(**options.__dict__) local_vars = locals() local_vars['pprint'] = pprint try: import bpython bpython.embed(locals_=local_vars) except ImportError: from yakumo import console console.Console(locals_=local_vars).interact()
def run_ptipython(): imported_objects = self.get_imported_objects(options) history_filename = os.path.expanduser('~/.ptpython_history') embed(user_ns=imported_objects, history_filename=history_filename, vi_mode=options.get('vi_mode', False), configure=run_config)
def command_shell(*args): ''' Runs a Python shell inside the application context. ''' context = None banner = 'Open Media Library' import db with db.session(): # Try BPython try: from bpython import embed embed(banner=banner, locals_=context) return except ImportError: pass # Try IPython try: try: # 0.10.x from IPython.Shell import IPShellEmbed ipshell = IPShellEmbed(banner=banner) ipshell(global_ns=dict(), local_ns=context) except ImportError: # 0.12+ from IPython import embed embed(banner1=banner, user_ns=context) return except ImportError: pass import code # Use basic python shell code.interact(banner, local=context)
def shell(): """Interactive stutuz console.""" from inspect import cleandoc from stutuz import db, models banner = '''\ Interactive stutuz console. Useful names: app Flask application for stutuz db The database instance models Namespace for all models ''' banner = cleandoc(banner) try: current_app.preprocess_request() context = dict(app=current_app, db=db, models=models) try: import bpython except ImportError: import code code.interact(banner, local=context) else: bpython.embed(context, ['-i'], banner) finally: current_app.process_response(current_app.response_class())
def run_ptpython(imported_objects, vi_mode=False): from ptpython.repl import embed, run_config history_filename = os.path.expanduser('~/.ptpython_history') embed(globals=imported_objects, history_filename=history_filename, vi_mode=vi_mode, configure=run_config)
def run(self, shell=None): """Runs a Python interactive interpreter.""" if not shell: shell = 'bpython' if shell == 'bpython': try: import bpython bpython.embed() except ImportError: shell = 'ipython' if shell == 'ipython': try: import IPython # Explicitly pass an empty list as arguments, because # otherwise IPython would use sys.argv from this script. shell = IPython.Shell.IPShell(argv=[]) shell.mainloop() except ImportError: shell = 'python' if shell == 'python': 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. readline.parse_and_bind("tab:complete") code.interact()
def pick_shell(banner, namespace): """ Picks and spawns an interactive shell choosing the first available option from: bpython, IPython and the default one. """ if not plain: # bpython try: import bpython except ImportError: pass else: bpython.embed(namespace, banner=banner) return # IPython try: import IPython except ImportError: pass else: sh = IPython.Shell.IPShellEmbed(banner=banner) sh(global_ns={}, local_ns=namespace) return # plain from code import interact interact(banner, local=namespace) return
def do_bpython_console(local): try: from bpython import embed except ImportError: raise ShellNotFound embed(banner=console_banner, locals_=local)
def run(self, no_ipython, no_bpython): """ Runs the shell. If no_bpython is False or use_bpython is True, then a BPython shell is run (if installed). Else, if no_ipython is False or use_python is True then a IPython shell is run (if installed). """ context = self.get_context() if not no_bpython: # Try BPython try: from bpython import embed embed(banner=self.banner, locals_=self.get_context()) return except ImportError: # Try IPython if not no_ipython: try: import IPython try: sh = IPython.Shell.IPShellEmbed(banner=self.banner) except AttributeError: sh = IPython.frontend.terminal.embed.InteractiveShellEmbed( banner1=self.banner) sh(global_ns=dict(), local_ns=context) return except ImportError: pass # Use basic python shell code.interact(self.banner, local=context)
def do_ipython_console(local): try: from IPython import embed except ImportError: raise ShellNotFound embed(banner1=console_banner, user_ns=local)
def bpython(): """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. """ from flask.globals import _app_ctx_stack from bpython.cli import main import bpython app = _app_ctx_stack.top.app 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()) bpython.embed(banner=banner, locals_=ctx)
def shell(app='ipython', banner=u'Interactive Inyoka Shell'): """Spawn a new interactive python shell :param app: choose between common python shell, ipython or bpython. Possible values are: python, ipython and bpython. """ assert app in ('python', 'ipython', 'bpython'), u'Your shell is not supported!' from code import interact from inyoka.core.api import ctx namespace = {'ctx': ctx} try: if app == 'python': interact(banner, local=namespace) elif app == 'ipython': import IPython sh = IPython.Shell.IPShellEmbed(banner=banner) sh(global_ns={}, local_ns=namespace) elif app == 'bpython': from bpython import embed embed(locals_=namespace, args=['-i', '-q']) else: raise ImportError() except ImportError: # fallback to default python interpreter from code import interact interact(banner, local=namespace)
def shell_command(): """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 its configuration. This is useful for executing small snippets of management code without having to manually configuring the application. """ import bpython from flask.globals import _app_ctx_stack app = _app_ctx_stack.top.app banner = 'Python %s on %s\nBPython: %s\nApp: %s%s\nInstance: %s\n' % ( sys.version, sys.platform, bpython.__version__, app.import_name, app.debug and ' [debug]' or '', 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()) bpython.embed(banner=banner, locals_=ctx)
def bpython(recipe, app=None, quiet=False, writable=True): from scif.main import ScifRecipe import bpython client = ScifRecipe(recipe, quiet=quiet, writable=writable) client.speak() if app is not None: client.activate(app) bpython.embed(locals_={'client': client})
def main(): locals_ = dict( [(name, cls) for name, cls in models.__dict__.items() if isinstance(cls, type)] ) with db_context() as db: locals_.update(db=db, pprint=pprint) bpython.embed(locals_=locals_)
def bpython(self): import bpython user_ns = self.get_start_namespace() if user_ns: bpython.embed(user_ns) else: bpython.embed()
def shell(): banner = 'byCycle Shell' try: import bpython except ImportError: printer.warning('bpython is not installed; falling back to python') code.interact(banner=banner) else: bpython.embed(banner=banner)
def bpython_console(self): """bpython console interpreter https://bpython-interpreter.org/ """ # pylint: disable=import-error import bpython bpython.embed(banner=self.banner) return 0
def run_bpython(client): '''give the user a bpython shell ''' try: import bpython except ImportError: return python(client) bpython.embed(locals_={'client': client})
def bpython(image): import bpython from sif.main import SIFHeader header = SIFHeader(image) bpython.embed(locals_={ 'header': header, 'image': image, 'SIFHeader': SIFHeader })
def bpython(): """Start a bpython shell.""" import bpython as bpy_shell # pylint: disable=import-error user_ns = get_start_namespace() if user_ns: bpy_shell.embed(user_ns) else: bpy_shell.embed()
def run_ptipython(): imported_objects = import_objects(options, self.style) history_filename = os.path.expanduser("~/.ptpython_history") embed( user_ns=imported_objects, history_filename=history_filename, vi_mode=options.get("vi_mode", False), configure=run_config, )
def bpython(self, shell_locals, banner): try: import bpython from bpython import embed except ImportError: return False banner = 'bpython {}\n{}'.format(bpython.__version__, banner) embed(locals_=shell_locals, banner=banner) return True
def invoke(cls, ns, banner): # pragma: nocover """ :param ns: local namespace :param banner: interactive shell startup banner Embed an interactive bpython shell. """ from bpython import embed embed(ns, ['-i'], banner)
def bpython(args): import bpython from sregistry.main import get_client client = get_client(args.endpoint) client.announce(args.command) from sregistry.database.models import Container, Collection bpython.embed(locals_={'client': cli, 'Container': Container, 'Collection': Collection})
def shell(_parser, cmd, args): # pragma: no cover """ Start an interactive python interpreter with pwny imported globally. """ parser = argparse.ArgumentParser( prog=_parser.prog, description=_parser.description, ) group = parser.add_mutually_exclusive_group() group.set_defaults(shell=have_bpython and 'bpython' or (have_IPython and 'ipython' or 'python')) if have_bpython: group.add_argument( '--bpython', action='store_const', dest='shell', const='bpython', help='Use the bpython interpreter' ) if have_IPython: group.add_argument( '--ipython', action='store_const', dest='shell', const='ipython', help='Use the IPython interpreter' ) group.add_argument( '--python', action='store_const', dest='shell', const='python', help='Use the default python interpreter' ) args = parser.parse_args(args) import pwny pwny_locals = dict( (key, getattr(pwny, key)) for key in dir(pwny) if not key.startswith('__') and not key == 'shell' ) if args.shell == 'bpython': from bpython import embed embed(pwny_locals, banner=BANNER) elif args.shell == 'ipython': from IPython import start_ipython start_ipython( argv=['--ext=pwnypack.ipython_ext'], ) else: import code code.interact(BANNER, local=pwny_locals)
def bpython(self, willful=True): """Run a bpython shell.""" try: import bpython except ImportError: if willful: req_missing(['bpython'], 'use the bpython console') raise # That’s how _execute knows whether to try something else. else: bpython.embed(banner=self.header.format('bpython'), locals_=self.context)
def run_bpython(image): """give the user a bpython shell""" client = prepare_client(image) try: import bpython except ImportError: return python(image) bpython.embed(locals_={"client": client})
def bpython(self, willful=True): """bpython shell.""" try: import bpython except ImportError as e: if willful: req_missing(["bpython"], "use the bpython console") raise e # That’s how _execute knows whether to try something else. else: bpython.embed(banner=self.header.format("bpython"), locals_=self.context)
def REPL(args, evpc): """ Open an interactive REPL (read-eval-print-loop) with access to evpc object """ msg = BANNER.format(evpc.id, evpc.name, evpc.region_name) if interpreter == 'bpython': bpython.embed(locals_=locals(), banner=msg) elif interpreter == 'ipython': IPython.embed(banner2=msg) elif interpreter is None: code.interact(local=locals(), banner=msg)
def shell(ctx): app = ctx.obj['app'] context = dict(app=app) with app.test_request_context(): try: from bpython import embed embed(locals_=context) return except ImportError: pass code.interact(local=context)
def open_console(self, **kwargs): # Opens up a bpython REPL. embedded_locals = { 'ohno': self.ohno } embedded_locals.update(kwargs) curses.curs_set(1) bpython.embed(locals_=embedded_locals) # Since bpython will modify our curses setup, we need to # reinitialize curses (nodelay, noecho, ..). self.ohno.ui.curses.start_curses()
def run_bpython(image): '''give the user a bpython shell ''' client = prepare_client(image) try: import bpython except ImportError: return python(image) bpython.embed(locals_={'client': client})
def start_python_console(namespace=None, noipython=False, banner=None): """Start Python console bound to the given namespace. If IPython or bpython are available, they will be started instead, unless `noipython` is True. If both IPython and bpython are available, IPython will be preferred. If neither is available, the built in console will be used, with tab completion enabled if on a system with readline. """ if namespace is None: namespace = {} if banner is None: banner = '' try: try: # use IPython if available if noipython: raise ImportError() try: from IPython.terminal.embed import InteractiveShellEmbed from IPython.terminal.ipapp import load_default_config except ImportError: from IPython.frontend.terminal.embed import InteractiveShellEmbed from IPython.frontend.terminal.ipapp import load_default_config except ImportError: pass else: config = load_default_config() shell = InteractiveShellEmbed( banner1=banner, user_ns=namespace, config=config) shell() return try: import bpython except ImportError: pass else: # start bpython bpython.embed(locals_=namespace, banner=banner) return import code try: # readline module is only available on unix systems import readline except ImportError: pass else: import rlcompleter readline.parse_and_bind("tab:complete") code.interact(banner=banner, local=namespace) except SystemExit: # raised when using exit() in python code.interact pass
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 handle_noargs(self, **options): from django.db.models.loading import get_models loaded_models = get_models() locals_ = {} for model in loaded_models: locals_[model.__name__] = model del loaded_models, model, options, get_models locals_.update(**locals()) locals_.pop('locals_') locals_.pop('self') import bpython bpython.embed(locals_)
def bpython(self): """bpython shell.""" from nikola import Nikola try: import conf except ImportError: print("No configuration found, cannot run the console.") else: import bpython SITE = Nikola(**conf.__dict__) SITE.scan_posts() bpython.embed(banner='Nikola Console (conf = configuration, SITE ' '= site engine)')
def bpython(self): """bpython shell.""" from nikola import Nikola try: import conf except ImportError: LOGGER.error("No configuration found, cannot run the console.") else: import bpython SITE = Nikola(**conf.__dict__) SITE.scan_posts() gl = {'conf': conf, 'SITE': SITE, 'Nikola': Nikola} bpython.embed(banner=self.header.format('bpython'), locals_=gl)
def interact(locals=None): savestdout = sys.stdout sys.stdout = sys.stderr try: import bpython banner = open(locals['__file__']).read() bpython.embed(locals, banner=banner) except ImportError: console = code.InteractiveConsole(locals) console.interact() sys.stdout = savestdout
def action(bpython=use_bpython): """Start a new interactive python session.""" namespace = init_func() if use_bpython: try: import bpython except ImportError: pass else: bpython.embed(locals_=namespace, banner=banner) return from code import interact interact(banner, local=namespace)
def interact(): """ Just run interace() anywhere in your code, and you'll get a sweet interactive bpython interpreter with access to the scope of where you called it. Great for investigating new API's. """ try: stack = inspect.stack() scope = stack[1][0] vars = scope.f_globals.copy() vars.update(scope.f_locals) finally: del stack bpython.embed(locals_=vars)
def run(shell='ipython'): '''Inicia o turtle e executa um terminal interativo para interagir com a aplicação''' start() if shell == 'ipython': import IPython IPython.embed() elif shell == 'bpython': import bpython print('embeding bpython shell') bpython.embed() else: raise ValueError('invalid shell: %s' % shell)
def run_bpython(env, help_): try: from bpython import embed except ImportError: raise ShellNotFound("bpython") return embed(locals_=env, banner=help_ + '\n')