def main(): # Set up a simple argument parser. parser = GreatFETArgumentParser( description="Convenience shell for working with GreatFET devices.") parser.add_argument('-e', '--exec', metavar="code", type=str, help="Executes the provided code as though it were passed" + "to a greatfet shell, and then terminates.", dest="code") args = parser.parse_args() gf = parser.find_specified_device() # Handle any inline execution. if args.code: # Replace any ;'s with newlines, so we can execute more than one statement. code = re.sub(";\s*", "\n", args.code) lines = code.split("\n") # And execute the code. for line in lines: result = repr(eval(line)) # Print the last result and return. print(result) sys.exit(0) # Break into IPython for the shell. print("Spwaning an IPython shell for easy access to your GreatFET.") print("Like normal python, you can use help(object) to get help for that object.") print("Try help(gf.apis.example) to see the documentation for the example API.\n") print("A GreatFET object has been created for you as 'gf'. Have fun!\n") IPython.start_ipython(user_ns={"gf": gf}, display_banner=False, argv=[])
def callback(brokers): models = Holder() for i, (path, broker) in enumerate(brokers): avail = _get_available_models(broker) if paths: if len(paths) > 1: models[paths[i]] = Models(broker, avail, __cwd, path, __coverage) else: models = Models(broker, avail, __cwd, path, __coverage) else: models = Models(broker, avail, __cwd, path, __coverage) if change_directory and len(brokers) == 1: __working_path, _ = brokers[0] os.chdir(__working_path) # disable jedi since it won't autocomplete for objects with__getattr__ # defined. IPython.core.completer.Completer.use_jedi = False __cfg = Config() __cfg.TerminalInteractiveShell.banner1 = Models.__doc__ __ns = {} __ns.update(globals()) __ns.update({"models": models}) if kernel: from ipykernel import kernelapp kernelapp.launch_new_instance([], user_ns=__ns, config=__cfg) else: IPython.start_ipython([], user_ns=__ns, config=__cfg)
def ipython(): c = config.slack.client s = config.slack import IPython dict_ = globals() dict_.update(locals()) IPython.start_ipython(argv=[], user_ns=dict_)
def open_console(self, w, given_commands=None): """ Start an interactive ipython console """ import sisyphus user_ns = { 'tk': sisyphus.toolkit, 'config_files': self.args.config_files, } # TODO Update welcome message welcome_msg = """ Info: IPCompleter.greedy = True is set to True. This allows to auto complete lists and dictionaries entries, but may evaluates functions on tab. Enter tk? for help""" run_commands = [] if given_commands: for c in given_commands: run_commands.append('print("Run command:", %s)' % repr(c)) run_commands.append(c) import IPython from traitlets.config.loader import Config c = Config() c.InteractiveShellApp.exec_lines = ['%rehashx'] + run_commands c.InteractiveShell.confirm_exit = False c.IPCompleter.greedy = True c.InteractiveShell.banner2 = welcome_msg with self.pause(): IPython.start_ipython(config=c, argv=[], user_ns=user_ns)
def ipython_interpreter(args): """An ipython interpreter is intended to be interactive, so it doesn't support running a script or arguments """ try: import IPython except ImportError: tty.die("ipython is not installed, install and try again.") if "PYTHONSTARTUP" in os.environ: startup_file = os.environ["PYTHONSTARTUP"] if os.path.isfile(startup_file): with open(startup_file) as startup: exec(startup.read()) # IPython can also support running a script OR command, not both if args.python_args: IPython.start_ipython(argv=args.python_args) elif args.python_command: IPython.start_ipython(argv=['-c', args.python_command]) else: header = ("Spack version %s\nPython %s, %s %s" % (spack.spack_version, platform.python_version(), platform.system(), platform.machine())) __name__ = "__main__" # noqa IPython.embed(module="__main__", header=header)
def main(logfile: str, limits: bool): import logging logging.basicConfig(level=logging.INFO, filename=logfile) logging.getLogger('urllib3').setLevel(logging.DEBUG) logging.getLogger('blockchain').setLevel(logging.DEBUG) logging.getLogger('channel_manager').setLevel(logging.DEBUG) logging.getLogger('ethevents').setLevel(logging.DEBUG) app = App() app.start(ignore_security_limits=not limits, endpoint_url='https://api.eth.events:433') if app.account.unlocked: es = elasticsearch.Elasticsearch( transport_class=MicroRaidenTransport, hosts=['api.eth.events:443'], use_ssl=True, session=app.session, timeout=30, ) IPython.start_ipython( user_ns=dict(es=es), argv=[], )
def shell(ns={}): try: import IPython IPython.start_ipython(user_ns=ns, display_banner=False, argv=[]) except ImportError: import code code.interact(local=ns)
def repl(engine_uri): # dynamic includes import IPython from traitlets.config import Config # First create a config object from the traitlets library c = Config() c.InteractiveShellApp.extensions = ["autoreload"] c.InteractiveShellApp.exec_lines = [ 'print("\\nBooting import Meltano REPL\\n")', "from meltano.core.project import Project", "from meltano.core.plugin import PluginRef, PluginInstall, Plugin", "from meltano.core.setting import Setting", "from meltano.core.plugin.settings_service import PluginSettingsService", "from meltano.core.config_service import ConfigService", "from meltano.core.db import project_engine", "from meltano.core.job import Job, State", "project = Project.find()", f"_, Session = project_engine(project, engine_uri='{engine_uri}', default=True)", "session = Session()", "%autoreload 2", ] # c.InteractiveShell.colors = 'LightBG' c.InteractiveShell.confirm_exit = False c.TerminalIPythonApp.display_banner = True # Now we start ipython with our configuration IPython.start_ipython(argv=[], config=c)
def start_repl(): """ Executes the samson REPL. """ import IPython import sys from samson import VERSION from traitlets.config import Config banner = f""" {LOGO} v{VERSION} -- https://github.com/wildcardcorp/samson Python {sys.version} IPython {IPython.__version__} """ conf = Config() conf.TerminalIPythonApp.display_banner = False conf.InteractiveShellApp.exec_lines = [ start_exec, f'print("""{banner}""")' ] conf.InteractiveShell.confirm_exit = False conf.TerminalInteractiveShell.term_title_format = f"samson v{VERSION}" IPython.start_ipython(config=conf)
def main_start(): # we check if we are called from an ipython session # we detect the presence of a running ipython by get_ipython being present in the # caller (or caller of caller, if called from pyHegel.start_pyHegel, and so one...) # However this will not work if the get_ipython function has been deleted. # Note that if we are running under IPython, there should be (since?) a __IPYTHON__ # with the value True n = 2 g = get_parent_globals(n) qt = which_qt() start_code = _start_code%qt while g is not None: if g.has_key('get_ipython'): # execute start_code in the already running ipython session. #print 'Under ipython', n exec(start_code, g) return n += 1 g = get_parent_globals(n) #print 'Outside ipython', n # We are not running in under an ipython session, start one. # need to fix before importing IPython (which imports time...) fix_scipy() import IPython # Force readlinelike behavior (completion in a list instead of a window) for newer ipython (5?) that uses prompt_toolkit try: if 'readlinelike' in IPython.terminal.interactiveshell.TerminalInteractiveShell.display_completions.values: IPython.terminal.interactiveshell.TerminalInteractiveShell.display_completions.default_value = 'readlinelike' except AttributeError: # display_completion not present pass IPython.start_ipython(argv=['--matplotlib=%s'%qt, '--InteractiveShellApp.exec_lines=%s'%start_code.split('\n')])
def NotebookSupport(_): # The following only reveals hidden imports to pyinstaller. if False: # pylint: disable=unused-variable import IPython.html.notebookapp import IPython.html.base.handlers import IPython.html.tree.handlers import IPython.html.auth.login import IPython.html.auth.logout import IPython.html.notebook.handlers import IPython.html.services.kernels.handlers import IPython.html.services.notebooks.handlers import IPython.html.services.clusters.handlers import IPython.kernel.ioloop import IPython.kernel.zmq.kernelapp import rekall.interactive import zmq.backend.cython import zmq.eventloop.ioloop argv = ["notebook", "-c", "from rekall import interactive; " "interactive.ImportEnvironment();", "--autocall", "2", "--notebook-dir", config.GetConfigFile().get("notebook_dir", config.GetHomeDir()) ] import IPython IPython.start_ipython(argv=argv) return True
def shell_command(ctx: Context): # pragma: no cover """ Run shell """ # Based on https://github.com/ei-grad/flask-shell-ipython app = ctx.obj if "IPYTHON_CONFIG" in app.settings: config = Config(app.settings["IPYTHON_CONFIG"]) else: config = load_default_config() config.TerminalInteractiveShell.banner1 = """ Python %s on %s IPython: %s App: %s [%s] Instance: %s """ % ( sys.version, sys.platform, IPython.__version__, type(app).__name__, app.import_name, app.root_path, ) sys.argv[0] = sys.argv[0] + " shell" IPython.start_ipython( argv=ctx.args, user_ns=app.make_shell_context(), config=config, )
def insp(ctx, src_path, interpreter): """Open a collection within an interactive interpreter. """ logger = logging.getLogger(__name__) banner = 'Fiona %s Interactive Inspector (Python %s)\n' \ 'Type "src.schema", "next(src)", or "help(src)" ' \ 'for more information.' \ % (fiona.__version__, '.'.join(map(str, sys.version_info[:3]))) try: with fiona.open(src_path) as src: scope = locals() if not interpreter: code.interact(banner, local=scope) elif interpreter == 'ipython': import IPython IPython.InteractiveShell.banner1 = banner IPython.start_ipython(argv=[], user_ns=scope) else: raise click.ClickException( 'Interpreter {} is unsupported or missing ' 'dependencies'.format(interpreter)) except Exception: logger.exception("Exception caught during processing") raise click.Abort()
def repl(): user_ns = {} py_main = __res.find('PY_MAIN') if py_main: mod_name, func_name = py_main.split(':', 1) try: import importlib mod = importlib.import_module(mod_name) user_ns = mod.__dict__ except: import traceback traceback.print_exc() if py_main and '__main__' not in user_ns: def run(args): if isinstance(args, basestring): import shlex args = shlex.split(args) import sys sys.argv = [sys.argv[0]] + args getattr(mod, func_name)() user_ns['__main__'] = run try: import IPython except ImportError: import code code.interact(local=user_ns) else: IPython.start_ipython(user_ns=user_ns)
def shell(): """Runs a shell in the app context. 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 configuring the application. """ import IPython from IPython.terminal.ipapp import load_default_config from traitlets.config.loader import Config from flask.globals import _app_ctx_stack app = _app_ctx_stack.top.app if 'IPYTHON_CONFIG' in app.config: config = Config(app.config['IPYTHON_CONFIG']) else: config = load_default_config() config.TerminalInteractiveShell.banner1 = 'Python %s on %s\nIPython: %s\nApp: %s%s\nInstance: %s' % ( sys.version, sys.platform, IPython.__version__, app.import_name, app.debug and ' [debug]' or '', app.instance_path) IPython.start_ipython(argv=[], config=config)
def insp(ctx, src_path, interpreter): verbosity = (ctx.obj and ctx.obj['verbosity']) or 2 logger = logging.getLogger('fio') banner = 'Fiona %s Interactive Inspector (Python %s)\n' \ 'Type "src.schema", "next(src)", or "help(src)" ' \ 'for more information.' \ % (fiona.__version__, '.'.join(map(str, sys.version_info[:3]))) try: with fiona.drivers(CPL_DEBUG=verbosity > 2): with fiona.open(src_path) as src: scope = locals() if not interpreter: code.interact(banner, local=scope) elif interpreter == 'ipython': import IPython IPython.InteractiveShell.banner1 = banner IPython.start_ipython(argv=[], user_ns=scope) else: raise click.ClickException( 'Interpreter {} is unsupported or missing ' 'dependencies'.format(interpreter)) except Exception: logger.exception("Exception caught during processing") raise click.Abort()
def insp(ctx, src_path, interpreter): verbosity = (ctx.obj and ctx.obj['verbosity']) or 2 logger = logging.getLogger('fio') banner = 'Fiona %s Interactive Inspector (Python %s)\n' \ 'Type "src.schema", "next(src)", or "help(src)" ' \ 'for more information.' \ % (fiona.__version__, '.'.join(map(str, sys.version_info[:3]))) try: with fiona.drivers(CPL_DEBUG=verbosity > 2): with fiona.open(src_path) as src: scope = locals() if not interpreter: code.interact(banner, local=scope) elif interpreter == 'ipython': import IPython IPython.InteractiveShell.banner1 = banner IPython.start_ipython(argv=[], user_ns=scope) else: raise click.ClickException( 'Interpreter %s is unsupported or missing ' 'dependencies' % interpreter) except Exception: logger.exception("Exception caught during processing") raise click.Abort()
def _start_repl(api): # type: (Iota) -> None """ Starts the REPL. """ banner = ( 'IOTA API client for {uri} ({testnet}) ' 'initialized as variable `api`.\n' 'Type `help(api)` for list of API commands.'.format( testnet='testnet' if api.testnet else 'mainnet', uri=api.adapter.get_uri(), ) ) scope_vars = {'api': api} try: # noinspection PyUnresolvedReferences import IPython except ImportError: # IPython not available; use regular Python REPL. from code import InteractiveConsole InteractiveConsole(locals=scope_vars).interact(banner, '') else: print(banner) IPython.start_ipython(argv=[], user_ns=scope_vars)
def main(): django.setup() create_result() print("Creating client") BaseResource._SHELL_CLIENT = ClientResourceManager() print("""Done! You can now lock resources and run tests, e.g. resource1 = ResourceClass.lock(skip_init=True, name='resource_name') resource2 = ResourceClass.lock(name='resource_name', config='config.json') shared_data['resource'] = resource1 run_test(ResourceBlock, parameter=5) run_test(ResourceBlock.params(parameter=6), resource=resource2) run_test(SomeTestCase, debug=True) """) startup_commands = [IMPORT_BLOCK_UTILS, IMPORT_RESOURCE_LOADER] startup_commands.append("imported_resources = get_resources();" "print('Importing resources:'); " "print(', '.join(imported_resources.keys()));" "globals().update(imported_resources)") startup_commands.extend(SHELL_STARTUP_COMMANDS) try: IPython.start_ipython(["-i", "--no-banner", "-c", ";".join(startup_commands)]) finally: print("Releasing locked resources...") BaseResource._SHELL_CLIENT.disconnect()
def shell_command(ipython_args): import IPython from IPython.terminal.ipapp import load_default_config from traitlets.config.loader import Config from flask.globals import _app_ctx_stack app = _app_ctx_stack.top.app banner = 'Python %s on %s\nIPython: %s\nApp: %s%s\nInstance: %s\n' % ( sys.version, sys.platform, IPython.__version__, app.import_name, app.debug and ' [debug]' or '', app.instance_path, ) ctx = {} if 'IPYTHON_CONFIG' in app.config: config = Config(app.config['IPYTHON_CONFIG']) else: config = load_default_config() config.TerminalInteractiveShell.banner1 = banner ctx.update(app.make_shell_context()) IPython.start_ipython(argv=ipython_args, user_ns=ctx, config=config)
def _start_shell(local_ns=None): import IPython user_ns = {} if local_ns: user_ns.update(local_ns) user_ns.update(globals()) IPython.start_ipython(argv=[], user_ns=user_ns)
def run(self, **options): ipython_options = list(options.get('ipython_options', [])) project = options.get('project') name = options.get('profile') if not (name and slugify(name)): active = self.settings.get('active') profiles_list = self.list_profiles( self.settings.get('path'), show_project=True) if active and active in profiles_list: if ':' in active: active_name, active_project = active.split(':') profile = Profile(active_name, project=active_project) else: profile = Profile(active, project=project) else: profile = None else: profile = Profile(name, project=project) if not profile: IPython.start_ipython(argv=ipython_options) return if not profile.exists(): self.red(texts.ERROR_PROFILE_DOESNT_EXIST_RUN.format(profile.name)) return self.settings.update({ 'last': profile.name }).save() profile.shell(ipython_options)
def _start_shell(local_ns=None): import IPython user_ns = {} if local_ns: user_ns.update(local_ns) user_ns.update(globals()) IPython.start_ipython(argv=[],user_ns=user_ns)
def spawn_shell(): """ Spawns the Tinymovr Studio IPython shell. """ version: str = pkg_resources.require("tinymovr")[0].version arguments: Dict[str, str] = docopt(__doc__, version=shell_name + " " + str(version)) logger = configure_logging() num_parser = pynumparser.NumberSequence(limits=(0, 16)) node_ids = num_parser(arguments["--ids"]) bustype: str = arguments["--bustype"] channel: str = arguments["--chan"] bitrate: int = int(arguments["--bitrate"]) do_version_check: bool = not arguments["--no-version-check"] if channel == "auto": channel = guess_channel(bustype_hint=bustype) can_bus: can.Bus = can.Bus(bustype=bustype, channel=channel, bitrate=bitrate) iface: IFace = CANBus(can_bus) tms: Dict = {} for node_id in node_ids: try: tm: UserWrapper = UserWrapper(node_id=node_id, iface=iface, version_check=do_version_check) tm_name: str = base_name + str(node_id) logger.info("Connected to " + tm_name) tms[tm_name] = tm except TimeoutError: logger.info("Node " + str(node_id) + " timed out") except IOError: logger.error("Node " + str(node_id) + " received abnormal message (possibly wrong ID?)") if len(tms) == 0: logger.error("No Tinymovr instances detected. Exiting shell...") else: tms_discovered: str = ", ".join(list(tms.keys())) user_ns: Dict = {} user_ns.update(tms) user_ns["tms"] = list(tms.values()) user_ns["plot"] = plot user_ns["ureg"] = get_registry() print(shell_name + " " + str(version)) print("Discovered instances: " + tms_discovered) print("Access Tinymovr instances as tmx, where x \ is the index starting from 1") print("e.g. the first Tinymovr instance will be tm1.") print("Instances are also available by index in the tms list.") c = Config() c.InteractiveShellApp.gui = "tk" c.TerminalIPythonApp.display_banner = False IPython.start_ipython(argv=[], config=c, user_ns=user_ns) logger.debug("Exiting shell...")
def _ipy(): """自動追加されるコマンド。ipython。""" import IPython m = sys.modules["__main__"] user_ns = {k: getattr(m, k) for k in dir(m)} IPython.start_ipython(argv=["--ext=autoreload"], user_ns=user_ns)
def repl(): user_ns = {} py_main = __res.find('PY_MAIN') if py_main: mod_name, func_name = py_main.split(':', 1) try: import importlib mod = importlib.import_module(mod_name) user_ns = mod.__dict__ except: import traceback traceback.print_exc() if py_main and '__main__' not in user_ns: def run(args): if isinstance(args, basestring): import shlex args = shlex.split(args) import sys sys.argv = [sys.argv[0]] + args getattr(mod, func_name)() user_ns['__main__'] = run try: import IPython except ImportError: import code code.interact(local=user_ns) else: IPython.start_ipython(user_ns=user_ns)
def main(): django.setup() print("Creating client") BaseResource._SHELL_CLIENT = ClientResourceManager() BaseResource._SHELL_CLIENT.connect() LogDebugHandler(None, sys.stdout, None) # Activate log to screen print("""Done! You can now lock resources and run tests, e.g. resource1 = ResourceClass.lock(skip_init=True, name='resource_name') resource2 = ResourceClass.lock(name='resource_name', config='config.json') shared_data['resource'] = resource1 run_block(ResourceBlock, parameter=5) run_block(ResourceBlock.params(parameter=6), resource=resource2) """) startup_commands = [IMPORT_BLOCK_UTILS, IMPORT_RESOURCE_LOADER] for app_name in SHELL_APPS: startup_commands.append("globals().update(get_resources(%r))" % app_name) startup_commands.extend(SHELL_STARTUP_COMMANDS) try: IPython.start_ipython(["-i", "-c", ";".join(startup_commands)]) finally: print("Releasing locked resources...") BaseResource._SHELL_CLIENT.disconnect()
def console(args): """ Start an interactive ipython console """ user_ns = { 'tk': sisyphus.toolkit, 'config_files': args.config_files, } if args.load: jobs = [sisyphus.toolkit.load_job(i) for i in args.load] user_ns['jobs'] = jobs for i, job in enumerate(jobs): print("jobs[%i]: %s" % (i, job)) elif not args.not_load_config: load_configs(args.config_files) # TODO Update welcome message welcome_msg = """ Info: IPCompleter.greedy = True is set to True. This allows to auto complete lists and dictionaries entries, but may evaluates functions on tab. Enter tk? for help""" import IPython from traitlets.config.loader import Config c = Config() c.InteractiveShell.banner2 = welcome_msg c.IPCompleter.greedy = True c.InteractiveShellApp.exec_lines = ['%rehashx'] + args.commands IPython.start_ipython(config=c, argv=[], user_ns=user_ns)
def shell(ctx): """Starts application shell.""" IPython.start_ipython(argv=[], user_ns={ "app": create_app(ctx.obj), "SETTINGS": SETTINGS })
def main(limits: bool, corsdomain: str): proxy, proxy_greenlet, app = run_proxy( endpoint_url='https://api.eth.events', ignore_security_limits=not limits, corsdomain=corsdomain, ) ui = UI(app) ui_methods = { '{}'.format(method_name): method for method_name, method in inspect.getmembers( ui, predicate=inspect.ismethod) if '__' not in method_name[:2] } if proxy is not None: queries = ethevents.examples.queries plots = ethevents.examples.plots es = Elasticsearch(['http://localhost:5478'], timeout=60) ee = UserNamespace(es, queries, plots, ui) IPython.start_ipython( user_ns=dict(ee=ee, es=es, queries=queries, plots=plots, **ui_methods, help=help), argv=[], ) proxy.stop() proxy_greenlet.join(timeout=5)
def launch_console(): global _CONNECTION global _SENSOR_TEMPLATES global _COLLECTOR_TEMPLATES parse_arguments() _CONNECTION = open_connection() _SENSOR_TEMPLATES = dict(DEFAULT_SENSOR_TEMPLATES) _COLLECTOR_TEMPLATES = dict(DEFAULT_COLLECTOR_TEMPLATES) init_console_functions() if 'init-script' in _CONFIG: exec _CONFIG['init-script'] in _CONSOLE_SCOPE try: import IPython print _BANNER IPython.start_ipython(user_ns=_CONSOLE_SCOPE) except ImportError as e: code.InteractiveConsole( locals=_CONSOLE_SCOPE).interact(_BANNER + _IPYTHON_NOTICE)
def main(): args = parse_args() archives = args.archives if args.debug: logging.basicConfig(level=logging.DEBUG) excludes = parse_exclude(args.exclude) if args.exclude else ["*.log"] conf = analyze(archives, excludes) # noqa F841 / unused var # import all the built-in predicates from insights.parsr.query import (lt, le, eq, gt, ge, isin, contains, # noqa: F401,F403 startswith, endswith, ieq, icontains, istartswith, iendswith, matches, make_child_query) q = make_child_query import IPython from traitlets.config.loader import Config ns = dict(locals()) ns["analyze"] = analyze ns["ALL"] = None ns["ANY"] = None IPython.core.completer.Completer.use_jedi = False c = Config() c.TerminalInteractiveShell.banner1 = banner IPython.start_ipython([], user_ns=ns, config=c)
def shell(self): use_ipython = False command = self.args.get('<command>') or '' try: import IPython except: self.logger.warn("you should pip install ipython for convenience") else: use_ipython = True # ipython if use_ipython: c = Config() c.InteractiveShellApp.exec_lines = [ 'from omegaml.client.util import get_omega', 'om = get_omega(shell_args)', 'print("omegaml is available as the om variable")', ] c.TerminalIPythonApp.display_banner = False argv = f'-c {command}'.split(' ') if command else [] IPython.start_ipython(argv, config=c, user_ns=dict(shell_args=self.args)) return # default console import code om = get_omega(self.args) try: import gnureadline except: self.logger.warn( "you should pip install gnureadline for convenience") variables = {} variables.update(locals()) shell = code.InteractiveConsole(locals=variables) shell.interact()
def do(interactive: bool, query: str, paths: List[str]) -> None: """Execute a query or enter interactive mode.""" if not query or query == "-": namespace = {"Query": Query, "START": START, "SYMBOL": SYMBOL, "TOKEN": TOKEN} try: import IPython IPython.start_ipython(argv=[], user_ns=namespace) except ImportError: import code as _code _code.interact(local=namespace) finally: return code = compile(query, "<console>", "eval") result = eval(code) # noqa eval() - developer tool, hopefully they're not dumb if isinstance(result, Query): if result.retcode: exc = click.ClickException("query failed") exc.exit_code = result.retcode raise exc result.diff(interactive=interactive) elif result: click.echo(repr(result))
def explore(ctx: Context): scope_vars = Interactive(ctx.database, ctx.repository).setup() config = Config() config.InteractiveShellApp.extensions = ctx.ipython_extensions config.InteractiveShellApp.profile = "sapp" config.InteractiveShellApp.display_banner = False IPython.start_ipython(argv=[], user_ns=scope_vars, config=config)
def run_shell(argv=[]): config = IPython.Config( TerminalInteractiveShell={ 'banner2': '*** RMQ shell ***' } ) IPython.start_ipython(argv=argv, config=config, user_ns=get_namespace())
def open_interpreter(model, message=None, variables=None, funcs=None): """ Opens an (I)Python interpreter Args: model (YATSM model): Pass YATSM model to work with message (str, optional): Additional message to pass to user in banner variables (dict of objects, optional): Variables available in (I)Python session funcs (dict of callable, optional): Functions available in (I)Python session """ local = dict(_funcs, model=model, np=np, plt=plt) if variables: local.update(variables) if funcs: local.update(funcs) banner = """\ YATSM {yver} Interactive Interpreter (Python {pver}) Type "help(model)" for info on YATSM model methods. NumPy and matplotlib.pyplot are already imported as "np" and "plt". """.format(yver=__version__, pver='.'.join(map(str, sys.version_info[:3])), funcs='\n\t'.join([k for k in local])) banner = textwrap.dedent(banner) if isinstance(message, str): banner += '\n' + message try: import IPython IPython.InteractiveShell.banner1 = banner IPython.start_ipython(argv=[], user_ns=local) except: code.interact(banner, local=local)
def _start_shell(local_ns=None): # An interactive shell is useful for debugging/development. import IPython user_ns = {} if local_ns: user_ns.update(local_ns) user_ns.update(globals()) IPython.start_ipython(argv=[], user_ns=user_ns)
def _run(self): # pylint: disable=method-hidden self.interrupt.wait() print('\n' * 2) print('Entering Console' + OKGREEN) print('Tip:' + OKBLUE) print_usage() # Remove handlers that log to stderr root = getLogger() for handler in root.handlers[:]: if isinstance(handler, StreamHandler) and handler.stream == sys.stderr: root.removeHandler(handler) stream = io.StringIO() handler = StreamHandler(stream=stream) handler.formatter = Formatter(u'%(levelname)s:%(name)s %(message)s') root.addHandler(handler) def lastlog(n=10, prefix=None, level=None): """ Print the last `n` log lines to stdout. Use `prefix='p2p'` to filter for a specific logger. Use `level=INFO` to filter for a specific level. Level- and prefix-filtering are applied before tailing the log. """ lines = (stream.getvalue().strip().split('\n') or []) if prefix: lines = [ line for line in lines if line.split(':')[1].startswith(prefix) ] if level: lines = [ line for line in lines if line.split(':')[0] == level ] for line in lines[-n:]: print(line) self.console_locals['lastlog'] = lastlog err = io.StringIO() sys.stderr = err def lasterr(n=1): """ Print the last `n` entries of stderr to stdout. """ for line in (err.getvalue().strip().split('\n') or [])[-n:]: print(line) self.console_locals['lasterr'] = lasterr IPython.start_ipython(argv=['--gui', 'gevent'], user_ns=self.console_locals) self.interrupt.clear() sys.exit(0)
def _run(self): self.interrupt.wait() print('\n' * 3) print("Entering Console") print("Tip: use loglevel `-l:error` to avoid logs") print(">> help(eth)") IPython.start_ipython(argv=['--gui', 'gevent'], user_ns=self.console_locals) self.interrupt.clear() sys.exit(0)
def _EmbedIPython(variables, argv=None): """Drops into an IPython REPL with variables available for use. Args: variables: A dict of variables to make available. Keys are variable names. Values are variable values. argv: The argv to use for starting ipython. Defaults to an empty list. """ import IPython # pylint: disable=g-import-not-at-top argv = argv or [] IPython.start_ipython(argv=argv, user_ns=variables)
def _run(self): # looping did not work self.interrupt.wait() print '\n' * 3 print "Entering Console, stopping services" for s in self.app.services.values(): if s != self: s.stop() IPython.start_ipython(argv=['--gui', 'gevent'], user_ns=self.console_locals) self.interrupt.clear() sys.exit(0)
def abicomp_time(options): """ Analyze/plot the timing data of single or multiple runs. """ paths = options.paths from abipy.abio.timer import AbinitTimerParser if len(options.paths) == 1 and os.path.isdir(paths[0]): # Scan directory tree top = options.paths[0] print("Walking directory tree from top:", top, "Looking for file extension:", options.ext) parser, paths_found, okfiles = AbinitTimerParser.walk(top=top, ext=options.ext) if not paths_found: cprint("Empty file list!", color="magenta") return 1 print("Found %d files\n" % len(paths_found)) if okfiles != paths_found: badfiles = [f for f in paths_found if f not in okfiles] cprint("Cannot parse timing data from the following files:", color="magenta") for bad in badfiles: print(bad) else: # Parse list of files. parser = AbinitTimerParser() okfiles = parser.parse(options.paths) if okfiles != options.paths: badfiles = [f for f in options.paths if f not in okfiles] cprint("Cannot parse timing data from the following files:", color="magenta") for bad in badfiles: print(bad) if parser is None: cprint("Cannot analyze timing data. parser is None", color="magenta") return 1 print(parser.summarize()) if options.verbose: for timer in parser.timers(): print(timer.get_dataframe()) if options.ipython: cprint("Invoking ipython shell. Use parser to access the object inside ipython", color="blue") import IPython IPython.start_ipython(argv=[], user_ns={"parser": parser}) elif options.notebook: parser.make_and_open_notebook(foreground=options.foreground) else: parser.plot_all() return 0
def shell(args=None): """Start an IPython shell hooked up to the jupyerhub database""" from .app import JupyterHub hub = JupyterHub() hub.load_config_file(hub.config_file) db_url = hub.db_url db = orm.new_session_factory(db_url, **hub.db_kwargs)() ns = {'db': db, 'db_url': db_url, 'orm': orm} import IPython IPython.start_ipython(args, user_ns=ns)
def main(banner, dataset, alt_interpreter=None): """ Main entry point for use with python interpreter """ local = dict(funcs, src=dataset, np=numpy, rio=rasterio, plt=plt) if not alt_interpreter: code.interact(banner, local=local) elif alt_interpreter == 'ipython': # pragma: no cover import IPython IPython.InteractiveShell.banner1 = banner IPython.start_ipython(argv=[], user_ns=local) else: raise ValueError("Unsupported interpreter '%s'" % alt_interpreter) return 0
def main(): """Start shell with `user` object """ ACCESS_TOKEN = sys.argv[1] flickr_api.set_auth_handler(ACCESS_TOKEN) user_namespace = { 'flickr_api': flickr_api, 'user': flickr_api.test.login()} # iPython uses `sys.argv` # so we're resetting it sys.argv = sys.argv[:1] IPython.start_ipython(user_ns=user_namespace)
def NotebookSupport(user_session): engine = user_session.ipython_engine if not engine: return False if engine == "notebook": argv = ["notebook", "-c", "from rekall import interactive; " "interactive.ImportEnvironment();", "--autocall", "2"] import IPython IPython.start_ipython(argv=argv) return True else: raise RuntimeError("Unknown ipython mode %s" % engine)
def _open_local_shell(self): imported_objects = self.get_imported_objects() try: import IPython except ImportError: IPython = None if IPython: IPython.start_ipython( argv=[], user_ns=imported_objects, banner1='Welcome to the lymph shell' ) else: import code code.interact(local=imported_objects)
def __call__(self, options): """Execute this command.""" namespace = {} # The namespace that code will run in. variables = {} # Descriptions of the namespace variables. # If a profile has been selected, set up a `bones` session and a # `viscera` origin in the default namespace. if options.profile_name is not None: session = bones.SessionAPI.fromProfileName(options.profile_name) namespace["session"] = session variables["session"] = ( "A `bones` session, configured for %s." % options.profile_name) origin = viscera.Origin(session) namespace["origin"] = origin variables["origin"] = ( "A `viscera` origin, configured for %s." % options.profile_name) if sys.stdin.isatty() and sys.stdout.isatty(): # We at a fully interactive terminal — i.e. stdin AND stdout are # connected to the TTY — so display some introductory text... banner = ["{automagenta}Welcome to the MAAS shell.{/automagenta}"] if len(variables) > 0: banner += ["", "Predefined variables:", ""] banner += [ "{autoyellow}%10s{/autoyellow}: %s" % variable for variable in sorted(variables.items()) ] for line in banner: print(colorized(line)) # ... then start IPython, or the plain familiar Python REPL if # IPython is not installed. try: import IPython except ImportError: code.InteractiveConsole(namespace).interact(" ") else: IPython.start_ipython( argv=[], display_banner=False, user_ns=namespace) else: # Either stdin or stdout is NOT connected to the TTY, so simply # slurp from stdin and exec in the already created namespace. source = sys.stdin.read() exec(source, namespace, namespace)
def launch_ipython_5_shell(args): """Open the SolveBio shell (IPython wrapper) with IPython 5+""" import IPython # noqa from traitlets.config import Config c = Config() path = os.path.dirname(os.path.abspath(__file__)) try: # see if we're already inside IPython get_ipython # pylint: disable=undefined-variable _print("WARNING: Running IPython within IPython.") except NameError: c.InteractiveShell.banner1 = 'SolveBio Python shell started.\n' c.InteractiveShellApp.exec_files = ['{}/ipython_init.py'.format(path)] IPython.start_ipython(argv=[], config=c)
def main_start(): # we check if we are called from an ipython session # we detect the presence of a running ipython by get_ipython being present in the # caller (or caller of caller, if called from pyHegel.start_pyHegel, and so one...) # However this will not work if the get_ipython function has been deleted. n = 2 g = get_parent_globals(n) while g != None: if g.has_key('get_ipython'): # execute start_code in the already running ipython session. #print 'Under ipython', n exec(_start_code, g) return n += 1 g = get_parent_globals(n) #print 'Outside ipython', n # We are not running in under an ipython session, start one. # need to fix before importing IPython (which imports time...) fix_scipy() import IPython IPython.start_ipython(argv=['--matplotlib=qt', '--InteractiveShellApp.exec_lines=%s'%_start_code.split('\n')])
def open_interpreter(model, message=None, variables=None, funcs=None): """ Opens an (I)Python interpreter Args: model (YATSM model): Pass YATSM model to work with message (str, optional): Additional message to pass to user in banner variables (dict of objects, optional): Variables available in (I)Python session funcs (dict of callable, optional): Functions available in (I)Python session """ local = dict(_funcs, model=model, np=np, plt=plt) if variables: local.update(variables) if funcs: local.update(funcs) banner = """\ YATSM {yver} Interactive Interpreter (Python {pver}) Type "help(model)" for info on YATSM model methods. NumPy and matplotlib.pyplot are already imported as "np" and "plt". """.format( yver=__version__, pver='.'.join(map(str, sys.version_info[:3])), funcs='\n\t'.join([k for k in local]) ) banner = textwrap.dedent(banner) if isinstance(message, str): banner += '\n' + message try: import IPython IPython.InteractiveShell.banner1 = banner IPython.start_ipython(argv=[], user_ns=local) except: code.interact(banner, local=local)
def shell(ipython_args): """Runs a shell in the app context. 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 configuring the application. """ import IPython from IPython.terminal.ipapp import load_default_config from traitlets.config.loader import Config from flask.globals import _app_ctx_stack app = _app_ctx_stack.top.app if 'IPYTHON_CONFIG' in app.config: config = Config(app.config['IPYTHON_CONFIG']) else: config = load_default_config() config.TerminalInteractiveShell.banner1 = '''Python %s on %s IPython: %s App: %s [%s] Instance: %s''' % (sys.version, sys.platform, IPython.__version__, app.import_name, app.env, app.instance_path) IPython.start_ipython( argv=ipython_args, user_ns=app.make_shell_context(), config=config, )
def _run(self): # pylint: disable=method-hidden # Remove handlers that log to stderr root = logging.getLogger() for handler in root.handlers[:]: if isinstance(handler, logging.StreamHandler) and handler.stream == sys.stderr: root.removeHandler(handler) stream = io.StringIO() handler = logging.StreamHandler(stream=stream) handler.formatter = logging.Formatter(u'%(levelname)s:%(name)s %(message)s') root.addHandler(handler) err = io.StringIO() sys.stderr = err def lastlog(n=10, prefix=None, level=None): """ Print the last `n` log lines to stdout. Use `prefix='p2p'` to filter for a specific logger. Use `level=INFO` to filter for a specific level. Level- and prefix-filtering are applied before tailing the log. """ lines = (stream.getvalue().strip().split('\n') or []) if prefix: lines = [ line for line in lines if line.split(':')[1].startswith(prefix) ] if level: lines = [ line for line in lines if line.split(':')[0] == level ] for line in lines[-n:]: print(line) def lasterr(n=1): """ Print the last `n` entries of stderr to stdout. """ for line in (err.getvalue().strip().split('\n') or [])[-n:]: print(line) tools = ConsoleTools( self.app.raiden, self.app.discovery, self.app.config['settle_timeout'], ) self.console_locals = { 'app': self.app, 'raiden': self.app.raiden, 'chain': self.app.raiden.chain, 'discovery': self.app.discovery, 'tools': tools, 'lasterr': lasterr, 'lastlog': lastlog, 'usage': print_usage, } print('\n' * 2) print('Entering Console' + OKGREEN) print('Tip:' + OKBLUE) print_usage() IPython.start_ipython(argv=['--gui', 'gevent'], user_ns=self.console_locals) sys.exit(0)
def run_shell(): config = IPython.config.loader.Config() config.InteractiveShellEmbed.confirm_exit = False IPython.start_ipython(config=config, user_ns=ns)
BaseAdapter.close_all_instances('rollback') else: if not plain: if bpython: try: import bpython bpython.embed(locals_=_env) return except: logger.warning( 'import bpython error; trying ipython...') else: try: import IPython if IPython.__version__ > '1.0.0': IPython.start_ipython(user_ns=_env) return elif IPython.__version__ == '1.0.0': from IPython.terminal.embed import InteractiveShellEmbed shell = InteractiveShellEmbed(user_ns=_env) shell() return elif IPython.__version__ >= '0.11': from IPython.frontend.terminal.embed import InteractiveShellEmbed shell = InteractiveShellEmbed(user_ns=_env) shell() return else: # following 2 lines fix a problem with # IPython; thanks Michael Toomim if '__builtins__' in _env:
try: import os, IPython os.environ['PYTHONSTARTUP'] = '' # Prevent running this again IPython.start_ipython() raise SystemExit except ImportError: pass
def _run(self): while True: self.interrupt.wait() IPython.start_ipython(argv=['--gui', 'gevent'], user_ns=self.console_locals) self.interrupt.clear()
def interact(mydict=None,argv=None,mybanner=None,loglevel=20): global session import code,sys,pickle,os,getopt,re from .config import conf conf.interactive = True if loglevel is not None: conf.logLevel=loglevel the_banner = "Welcome to kamene (%s)" if mybanner is not None: the_banner += "\n" the_banner += mybanner if argv is None: argv = sys.argv import atexit try: import rlcompleter,readline except ImportError: log_loading.info("Can't load Python libreadline or completer") READLINE=0 else: READLINE=1 class KameneCompleter(rlcompleter.Completer): def global_matches(self, text): matches = [] n = len(text) for lst in [dir(builtins), session.keys()]: for word in lst: if word[:n] == text and word != "__builtins__": matches.append(word) return matches def attr_matches(self, text): m = re.match(r"(\w+(\.\w+)*)\.(\w*)", text) if not m: return expr, attr = m.group(1, 3) try: object = eval(expr) except: object = eval(expr, session) if isinstance(object, Packet) or isinstance(object, Packet_metaclass): #words = filter(lambda x: x[0]!="_",dir(object)) words = [ x for x in dir(object) if x[0]!="_" ] words += [x.name for x in object.fields_desc] else: words = dir(object) if hasattr( object,"__class__" ): words = words + rlcompleter.get_class_members(object.__class__) matches = [] n = len(attr) for word in words: if word[:n] == attr and word != "__builtins__": matches.append("%s.%s" % (expr, word)) return matches readline.set_completer(KameneCompleter().complete) readline.parse_and_bind("C-o: operate-and-get-next") readline.parse_and_bind("tab: complete") session=None session_name="" STARTUP_FILE = DEFAULT_STARTUP_FILE PRESTART_FILE = DEFAULT_PRESTART_FILE iface = None try: opts=getopt.getopt(argv[1:], "hs:Cc:Pp:d") for opt, parm in opts[0]: if opt == "-h": _usage() elif opt == "-s": session_name = parm elif opt == "-c": STARTUP_FILE = parm elif opt == "-C": STARTUP_FILE = None elif opt == "-p": PRESTART_FILE = parm elif opt == "-P": PRESTART_FILE = None elif opt == "-d": conf.logLevel = max(1,conf.logLevel-10) if len(opts[1]) > 0: raise getopt.GetoptError("Too many parameters : [%s]" % " ".join(opts[1])) except getopt.GetoptError as msg: log_loading.error(msg) sys.exit(1) if PRESTART_FILE: _read_config_file(PRESTART_FILE) kamene_builtins = __import__("kamene.all",globals(),locals(),".").__dict__ builtins.__dict__.update(kamene_builtins) globkeys = list(kamene_builtins.keys()) globkeys.append("kamene_session") kamene_builtins=None # XXX replace with "with" statement if mydict is not None: builtins.__dict__.update(mydict) globkeys += mydict.keys() conf.color_theme = DefaultTheme() if STARTUP_FILE: _read_config_file(STARTUP_FILE) if session_name: try: os.stat(session_name) except OSError: log_loading.info("New session [%s]" % session_name) else: try: try: session = pickle.load(gzip.open(session_name,"rb")) except IOError: session = pickle.load(open(session_name,"rb")) log_loading.info("Using session [%s]" % session_name) except EOFError: log_loading.error("Error opening session [%s]" % session_name) except AttributeError: log_loading.error("Error opening session [%s]. Attribute missing" % session_name) if session: if "conf" in session: conf.configure(session["conf"]) session["conf"] = conf else: conf.session = session_name session={"conf":conf} else: session={"conf": conf} builtins.__dict__["kamene_session"] = session if READLINE: if conf.histfile: try: readline.read_history_file(conf.histfile) except IOError: pass atexit.register(kamene_write_history_file,readline) atexit.register(kamene_delete_temp_files) IPYTHON=False if conf.interactive_shell.lower() == "ipython": try: import IPython IPYTHON=True except ImportError as e: log_loading.warning("IPython not available. Using standard Python shell instead.") IPYTHON=False if IPYTHON: banner = the_banner % (conf.version) + " using IPython %s" % IPython.__version__ if conf.ipython_embedded: IPython.embed(user_ns=session, banner2=banner) else: IPython.start_ipython(argv=[], user_ns=session) else: code.interact(banner = the_banner % (conf.version), local=session, readfunc=conf.readfunc) if conf.session: save_session(conf.session, session) for k in globkeys: try: del(builtins.__dict__[k]) except: pass
def main(): def str_examples(): return """\ Usage example: abistruct.py convert filepath cif => Read the structure from file and print CIF file. abistruct.py convert filepath abivars => Print the ABINIT variables defining the structure. abistruct.py convert out_HIST abivars => Read the last structure from the HIST file and print the corresponding Abinit variables. abistruct.py visualize filepath xcrysden => Visualize the structure with XcrysDen. abistruct.py ipython filepath => Read structure from filepath and open Ipython terminal. abistruct.py bz filepath => Read structure from filepath, plot BZ with matplotlib. abistruct.py pmgdata mp-149 => Get structure from pymatgen database and print its JSON representation. """ def show_examples_and_exit(err_msg=None, error_code=1): """Display the usage of the script.""" sys.stderr.write(str_examples()) if err_msg: sys.stderr.write("Fatal Error\n" + err_msg + "\n") sys.exit(error_code) # Parent parser for commands that need to know the filepath path_selector = argparse.ArgumentParser(add_help=False) path_selector.add_argument('filepath', nargs="?", help="File with the crystalline structure") parser = argparse.ArgumentParser(epilog=str_examples(), formatter_class=argparse.RawDescriptionHelpFormatter) parser.add_argument('-V', '--version', action='version', version="%(prog)s version " + abilab.__version__) # Parent parser for common options. copts_parser = argparse.ArgumentParser(add_help=False) copts_parser.add_argument('-v', '--verbose', default=0, action='count', # -vv --> verbose=2 help='verbose, can be supplied multiple times to increase verbosity') copts_parser.add_argument('--loglevel', default="ERROR", type=str, help="set the loglevel. Possible values: CRITICAL, ERROR (default), WARNING, INFO, DEBUG") # Create the parsers for the sub-commands subparsers = parser.add_subparsers(dest='command', help='sub-command help', description="Valid subcommands, use command --help for help") # Subparser for convert command. p_convert = subparsers.add_parser('convert', parents=[copts_parser, path_selector], help="Convert structure to the specified format.") p_convert.add_argument('format', nargs="?", default="cif", type=str, help="Format of the output file (cif, cssr, POSCAR, json, mson, abivars).") # Subparser for ipython. p_ipython = subparsers.add_parser('ipython', parents=[copts_parser, path_selector], help="Open IPython shell for advanced operations on structure object.") # Subparser for bz. p_bz = subparsers.add_parser('bz', parents=[copts_parser, path_selector], help="Read structure from file, plot Brillouin zone with matplotlib.") # Subparser for visualize command. p_visualize = subparsers.add_parser('visualize', parents=[copts_parser, path_selector], help="Visualize the structure with the specified visualizer") p_visualize.add_argument('visualizer', nargs="?", default="xcrysden", type=str, help=("Visualizer name. " "List of visualizer supported: %s" % ", ".join(Visualizer.all_visunames()))) # Subparser for pmgid command. p_pmgdata = subparsers.add_parser('pmgdata', parents=[copts_parser], help="Get structure from the pymatgen database. Requires internet connection and MAPI_KEY") p_pmgdata.add_argument("pmgid", type=str, default=None, help="Pymatgen identifier") p_pmgdata.add_argument("--mapi-key", default=None, help="Pymatgen MAPI_KEY. Use env variable if not specified.") p_pmgdata.add_argument("--endpoint", default="www.materialsproject.org", help="Pymatgen database.") # Subparser for animate command. p_animate = subparsers.add_parser('animate', parents=[copts_parser, path_selector], help="Read structures from HIST or XDATCAR. Print structures in Xrysden AXSF format to stdout") # Parse command line. try: options = parser.parse_args() except Exception as exc: show_examples_and_exit(error_code=1) # loglevel is bound to the string value obtained from the command line argument. # Convert to upper case to allow the user to specify --loglevel=DEBUG or --loglevel=debug import logging numeric_level = getattr(logging, options.loglevel.upper(), None) if not isinstance(numeric_level, int): raise ValueError('Invalid log level: %s' % options.loglevel) logging.basicConfig(level=numeric_level) if options.command == "convert": structure = abilab.Structure.from_file(options.filepath) if options.format == "abivars": print(structure.abi_string) else: s = structure.convert(format=options.format) print(s) elif options.command == "ipython": structure = abilab.Structure.from_file(options.filepath) print("Invoking Ipython, `structure` object will be available in the Ipython terminal") import IPython IPython.start_ipython(argv=[], user_ns={"structure": structure}) elif options.command == "visualize": structure = abilab.Structure.from_file(options.filepath) structure.visualize(options.visualizer) elif options.command == "bz": structure = abilab.Structure.from_file(options.filepath) structure.show_bz() elif options.command == "pmgdata": # Get the Structure corresponding the a material_id. structure = abilab.Structure.from_material_id(options.pmgid, final=True, api_key=options.mapi_key, endpoint=options.endpoint) # Convert to json and print it. s = structure.convert(format="json") #s = structure.convert(format="mson") print(s) elif options.command == "animate": from abipy.iotools import xsf_write_structure filepath = options.filepath if any(filepath.endswith(ext) for ext in ("HIST", "HIST.nc")): with abilab.abiopen(filepath) as hist: structures = hist.structures elif "XDATCAR" in filepath: from pymatgen.io.vaspio import Xdatcar structures = Xdatcar(filepath).structures if not structures: raise RuntimeError("Your Xdatcar contains only one structure. Due to a bug " "in the pymatgen routine, your structures won't be parsed correctly" "Solution: Add another structure at the end of the file.") else: raise ValueError("Don't know how to handle file %s" % filepath) xsf_write_structure(sys.stdout, structures) else: raise ValueError("Unsupported command: %s" % options.command) return 0