def shell( username: str = OPTION_USERNAME, password: str = OPTION_PASSWORD, address: str = OPTION_ADDRESS, port: int = OPTION_PORT, verify: bool = OPTION_VERIFY, ) -> None: if embed is None or colored is None: typer.echo("ipython and termcolor required for shell subcommand") sys.exit(1) protect = ProtectApiClient(address, port, username, password, verify_ssl=verify) loop = asyncio.get_event_loop() loop.run_until_complete(protect.update(True)) _setup_logger(show_level=True) c = get_config() c.InteractiveShellEmbed.colors = "Linux" embed(header=colored("protect = ProtectApiClient(*args)", "green"), config=c, using="asyncio")
def _start_ipython(self): self._old_stdout = sys.stdout self._old_stderr = sys.stderr self._old_stdin = sys.stdin try: print('Starting IPython') print('ns:', self._user_ns) sys.stdout = self.fw_out sys.__stdout__ = self.fw_out sys.stdin = self.fr_in sys.__stdin__ = self.fr_in #sys.stderr = self.fw_out import IPython from traitlets.config import get_config c = get_config() c.InteractiveShellEmbed.colors = "Linux" IPython.embed(config=c, user_ns=self._user_ns, user_module=self._user_module) finally: sys.stdout = self._old_stdout sys.__stdout__ = self._old_stdout sys.stdin = self._old_stdin sys.__stdin__ = self._old_stdin sys.stderr = self._old_stderr
def _run_asyncio_ipython(loop, local_ns): import IPython, concurrent.futures original_run_cell = IPython.InteractiveShell.run_cell def run_cell_thread(self, *args, **kwargs): self.autoawait = False f = concurrent.futures.Future() def run(): f.set_result(original_run_cell(self, *args, **kwargs)) loop.call_soon_threadsafe(run) return f.result() IPython.InteractiveShell.run_cell = run_cell_thread from IPython import embed from traitlets.config import get_config _c = get_config() _c.InteractiveShellEmbed.colors = "Linux" IPython.terminal.embed.InteractiveShellEmbed(config=_c).mainloop( local_ns=local_ns) os._exit(0)
def shell( username: str = OPTION_USERNAME, password: str = OPTION_PASSWORD, address: str = OPTION_ADDRESS, port: int = OPTION_PORT, verify: bool = OPTION_VERIFY, new: bool = OPTION_NEW, ) -> None: if embed is None or colored is None: typer.echo("ipython and termcolor required for shell subcommand") sys.exit(1) if new: protect: Union[UpvServer, ProtectApiClient] = ProtectApiClient( address, port, username, password, verify_ssl=verify ) else: protect = UpvServer(None, address, port, username, password, verify_ssl=verify) loop = asyncio.get_event_loop() loop.run_until_complete(protect.update(True)) console_handler = logging.StreamHandler() console_handler.setLevel(logging.DEBUG) _LOGGER.setLevel(logging.DEBUG) _LOGGER.addHandler(console_handler) klass = "UpvServer" if new: klass = "ProtectApiClient" c = get_config() c.InteractiveShellEmbed.colors = "Linux" embed(header=colored(f"protect = {klass}(*args)", "green"), config=c, using="asyncio")
def ipython(**locals_): from IPython import start_ipython from traitlets.config import get_config c = get_config() c.TerminalInteractiveShell.banner2 = BANNER start_ipython(argv=[], config=c, user_ns=locals_)
def test_fails_with_args(self): c = get_config() c.ReportCmd.raise_config_file_errors = True c.ReportCmd.project = True with self.assertRaisesRegex(CmdException, "--project' takes no arguments, received"): list(report.ReportCmd(config=c).run('EXTRA_ARG'))
def test_output_input(self): c = get_config() c.ReportCmd.raise_config_file_errors = True c.ReportCmd.project = True with tempfile.TemporaryDirectory() as td: c.ProjectsDB.repo_path = td project.ProjectCmd.AddCmd(config=c).run('proj1') project.ProjectCmd.AddReportCmd(config=c).run('out=%s' % _out_fpath) cmd = report.ReportCmd(config=c) res = cmd.run() self.assertIsInstance(res, types.GeneratorType) res = list(res) self.assertEqual(len(res), 3) for i in res: self.assertIsInstance(i, pd.DataFrame) project.ProjectCmd.AddReportCmd(config=c).run('inp=%s' % _inp_fpath) cmd = report.ReportCmd(config=c) res = cmd.run() self.assertIsInstance(res, types.GeneratorType) res = list(res) self.assertEqual(len(res), 4) self.assertIsInstance(res[0], pd.Series) for i in res[1:]: self.assertIsInstance(i, pd.DataFrame)
def cli_shell(config, environment, system): """Run a shell with access to the database.""" # Suppress logging (e.g. on tab-completion) import logging logging.getLogger('parso.cache').setLevel(logging.WARNING) logging.getLogger('parso.python.diff').setLevel(logging.WARNING) logging.getLogger('urllib3.connectionpool').setLevel(logging.WARNING) logging.getLogger('asyncio').setLevel(logging.WARNING) del logging # Initialize the database try: ctx = server.init(config, environment, system) except error.ConfigNotFoundError: # Not good. Exit! sys.exit(1) server.app.app_context().push() db.sqla.create_all() # Run the iPython shell import IPython from traitlets.config import get_config c = get_config() c.InteractiveShellEmbed.colors = "Linux" print() IPython.embed(config=c)
def get_ipython_config(device): # import os, sys, IPython # os.environ['PYTHONSTARTUP'] = '' # Prevent running this again c = config.get_config() c.TerminalInteractiveShell.confirm_exit = False c.TerminalInteractiveShell.logstart = True c.TerminalInteractiveShell.logfile = '%s-interactive_aci.ipython.log' % device return c
def get_ipython_config(device): # import os, sys, IPython # os.environ['PYTHONSTARTUP'] = '' # Prevent running this again c = config.get_config() c.TerminalInteractiveShell.confirm_exit = False c.TerminalInteractiveShell.logstart = True c.TerminalInteractiveShell.logfile = '%s-interactive_aci.ipython.log' %device return c
def test_fails_when_no_project(self): c = get_config() c.ReportCmd.raise_config_file_errors = True c.ReportCmd.project = True with tempfile.TemporaryDirectory() as td: c.ProjectsDB.repo_path = td cmd = report.ReportCmd(config=c) with self.assertRaisesRegex(CmdException, r"No current-project exists yet!"): list(cmd.run())
def test_extract_output(self): c = get_config() c.ReportCmd.raise_config_file_errors = True cmd = report.ReportCmd(config=c) res = cmd.run('out=%s' % _out_fpath) self.assertIsInstance(res, types.GeneratorType) res = list(res) self.assertEqual(len(res), 3) for i in res: self.assertIsInstance(i, pd.DataFrame)
def test_gen_conf(self): c = get_config() c.MainCmd.raise_config_file_errors = True cmd = dice.GenConfigCmd(config=c) with tempfile.TemporaryDirectory() as td: conf_fpath = osp.join(td, 'cc.py') cmd.run(conf_fpath) self.assertTrue(osp.isfile(conf_fpath), (conf_fpath, os.listdir(osp.split(conf_fpath)[0]))) stat = os.stat(conf_fpath) self.assertGreater(stat.st_size, 7000, stat)
def test_extract_both(self): c = get_config() c.ReportCmd.raise_config_file_errors = True cmd = report.ReportCmd(config=c) res = cmd.run('inp=%s' % _inp_fpath, 'out=%s' % _out_fpath) self.assertIsInstance(res, types.GeneratorType) res = list(res) self.assertEqual(len(res), 4) self.assertIsInstance(res[0], pd.Series) for i in res[1:]: self.assertIsInstance(i, pd.DataFrame)
def test_fails_when_empty(self): c = get_config() c.ReportCmd.raise_config_file_errors = True c.ReportCmd.project = True with tempfile.TemporaryDirectory() as td: c.ProjectsDB.repo_path = td project.ProjectCmd.AddCmd(config=c).run('proj1') cmd = report.ReportCmd(config=c) with self.assertRaisesRegex( CmdException, r"Current project 'proj1' contains no input/output files!" ): list(cmd.run())
def cli_server_shell(ctx): """ Run a iPython shell. """ # shell.init(ctx.environment) c = get_config() c.InteractiveShellEmbed.colors = "Linux" # Suppress logging (e.g. on tab-completion) import logging logging.getLogger('parso.cache').setLevel(logging.WARNING) logging.getLogger('parso.python.diff').setLevel(logging.WARNING) logging.getLogger('urllib3.connectionpool').setLevel(logging.WARNING) logging.getLogger('asyncio').setLevel(logging.WARNING) del logging IPython.embed(config=c)
def start_ipython(options): colorama.init() comports = options.devices d = list() # Print out a mini intro to the interactive session -- # Start with white and then magenta to keep the session white # (workaround for a bug in ipython) colors = { "c_default": colorama.Fore.WHITE + colorama.Style.BRIGHT, "c_highlight": colorama.Fore.YELLOW + colorama.Style.BRIGHT, "c_text": colorama.Fore.CYAN + colorama.Style.BRIGHT } print(USAGE_STRING.format(**colors)) for dev_com in comports: d.append( Interactive( Uart(port=dev_com, baudrate=options.baudrate, device_name=dev_com.split("/")[-1]))) device = d[0] send = device.acidev.write_aci_cmd # NOQA: Ignore unused variable # Set iPython configuration c = config.get_config() if options.no_logfile: c.TerminalInteractiveShell.logstart = False c.InteractiveShellApp.db_log_output = False else: dt = DateTime.DateTime() logfile = "interactive_session_{}-{}-{}-{}.log".format( dt.yy(), dt.dayOfYear(), dt.hour(), dt.minute()) c.TerminalInteractiveShell.logstart = True c.InteractiveShellApp.db_log_output = True c.TerminalInteractiveShell.logfile = logfile c.TerminalInteractiveShell.confirm_exit = False c.InteractiveShellApp.multiline_history = True c.InteractiveShellApp.log_level = logging.DEBUG IPython.embed(config=c) for dev in d: dev.close() raise SystemExit(0)
def main(ipynb, kernel_name): print("running %s" % ipynb) nb = read(ipynb, as_version=4) config = get_config() config.BokehExecutePreprocessor.kernel_name = kernel_name print(config) ep = BokehExecutePreprocessor(config=config) ep.preprocess(nb, {'metadata': {'path': './'}}) exportHtml = HTMLExporter() (body, resources) = exportHtml.from_notebook_node(nb) outfile = ipynb + ".html" open(outfile, 'w').write(body) print("wrote %s" % outfile)
def ipython(): from app.database import db from app.main.models import User, Role from app.climbing.models import Session, Route from IPython import embed from traitlets.config import get_config c = get_config() c.InteractiveShellEmbed.colors = 'Linux' embed(user_ns={ 'db': db, 'User': User, 'Role': Role, 'Session': Session, 'Route': Route }, config=c)
def get_export_names(config=get_config()): """Return a list of the currently supported export targets Exporters can be found in external packages by registering them as an nbconvert.exporter entrypoint. """ exporters = sorted(entrypoints.get_group_named('nbconvert.exporters')) enabled_exporters = [] for exporter_name in exporters: try: e = get_exporter(exporter_name)(config=config) if e.enabled: enabled_exporters.append(exporter_name) except ExporterDisabledError: pass return enabled_exporters
def ipython(): """Open Ipython session""" from app.database import db from app.auditlog.models import Record, State, HrsaDesignation, Tag from IPython import embed from traitlets.config import get_config config = get_config() config.InteractiveShellEmbed.colors = 'Linux' embed(user_ns={ 'db': db, 'Record': Record, 'State': State, 'HrsaDesignation': HrsaDesignation, 'Tag': Tag, }, config=config)
def main(): parser = argparse.ArgumentParser() parser.add_argument( "-i", "--interactive", default=False, action="store_true", help= "Interactive mode with a `sandbox` instance available. Embeds an IPython shell." ) parser.add_argument("--no-vgpu", default=False, action="store_true", help="Disable the virtual GPU.") parser.add_argument("-s", "--logon-script", required=False, help="Logon script for non-interactive (ipy) sandbox.", default="") parser.add_argument("-f", "--folder", action="append", help="Folders to map to the sandbox.", default=[]) args = parser.parse_args() sandbox = winsandbox.new_sandbox(networking=args.interactive, virtual_gpu=not args.no_vgpu, logon_script=args.logon_script, folder_mappers=[ winsandbox.FolderMapper( folder_path=folder, read_only=False) for folder in args.folder ]) if args.interactive: config = get_config() config.InteractiveShellEmbed.colors = "Neutral" # Workaround to enable colors in embedded IPy. embed( config=config, header= 'Welcome to the Windows Sandbox!\nUse the `sandbox` object to control the sandbox.' )
def cmd_console(args): import code import platform d = u2.connect(args.serial) model = d.shell("getprop ro.product.model").output.strip() serial = d.serial try: import IPython from traitlets.config import get_config c = get_config() c.InteractiveShellEmbed.colors = "Linux" IPython.embed(config=c) except ImportError: _vars = globals().copy() _vars.update(locals()) shell = code.InteractiveConsole(_vars) shell.interact(banner="Python: %s\nDevice: %s(%s)" % (platform.python_version(), model, serial))
def get_exporter(name, config=get_config()): """Given an exporter name or import path, return a class ready to be instantiated Raises ExporterName if exporter is not found or ExporterDisabledError if not enabled """ if name == 'ipynb': name = 'notebook' try: exporter = entrypoints.get_single('nbconvert.exporters', name).load() if getattr(exporter(config=config), 'enabled', True): return exporter else: raise ExporterDisabledError( 'Exporter "%s" disabled in configuration' % (name)) except entrypoints.NoSuchEntryPoint: try: exporter = entrypoints.get_single('nbconvert.exporters', name.lower()).load() if getattr(exporter(config=config), 'enabled', True): return exporter else: raise ExporterDisabledError( 'Exporter "%s" disabled in configuration' % (name)) except entrypoints.NoSuchEntryPoint: pass if '.' in name: try: exporter = import_item(name) if getattr(exporter(config=config), 'enabled', True): return exporter else: raise ExporterDisabledError( 'Exporter "%s" disabled in configuration' % (name)) except ImportError: log = get_logger() log.error("Error importing %s" % name, exc_info=True) raise ExporterNameError('Unknown exporter "%s", did you mean one of: %s?' % (name, ', '.join(get_export_names())))
def main(): def shortname(v, k): return getattr(v, '__name__', k).split('.')[-1] user_ns = { 'BASIC_KIT': BASIC_KIT, 'Chord': Chord, 'F': Fraction, 'Fraction': Fraction, 'Note': Note, 'PIANO': PIANO, 'Part': Part, 'Phrase': Phrase, 'dotted': lengths.dotted, 'double_whole': lengths.double_whole, 'drumkit': drumkit, 'eighth': lengths.eighth, 'half': lengths.half, 'manager': StageManager(), 'quarter': lengths.quarter, 'sixteenth': lengths.sixteenth, 'sixty_fourth': lengths.sixty_fourth, 'thirty_second': lengths.thirty_second, 'triplet': lengths.triplet, 'whole': lengths.whole, } c = get_config() c.InteractiveShellApp.exec_lines = [ '%gui pyglet', ] c.TerminalInteractiveShell.prompts_class = ClassicPrompts names = ', '.join(k if k == shortname(v, k) else f'{k} ({shortname(v, k)})' for k, v in sorted(user_ns.items())) + '\n' width, _ = get_terminal_size() names = '\n'.join(wrap(names, width - 5)) names = indent(names, ' ') c.InteractiveShell.banner2 = BANNER + names + '\n' c.InteractiveShell.confirm_exit = False c.InteractiveShellApp.display_banner = True start_ipython(config=c, user_ns=user_ns)
def handle(self, *args, **options): User = get_user_model() helpers = [ ("Date", "datetime, timedelta, time"), ("django.utils", "timezone, termcolors, dateformat, translation."), ("%quickref", "Quick reference."), ("User", "Django Auth Model"), ("help", "Python's own help system."), ("object?", "Details about 'object'"), ("object??", "More Details about 'object' "), ] registered_models = {} for model in apps.get_models(): module = model.__module__ name = model.__name__ locals()[name] = model try: registered_models[module].append(name) except: registered_models[module] = [name] for module in registered_models: helpers.append((module, ", ".join(registered_models[module]))) banner2 = "\n".join( ["%s: %s" % (colorize(x, fg="yellow"), y) for x, y in helpers]) + "\n" banner = "Hi! \n\n" \ "Here some useful shortcuts (Crtl-D to exit):" c = get_config() c.InteractiveShell.banner1 = banner c.InteractiveShell.banner2 = banner2 c.TerminalInteractiveShell.confirm_exit = False c.PromptManager.in_template = '$ ' c.PromptManager.out_template = '> ' embed(config=c)
def handle(self, *args, **options): User = get_user_model() helpers = [ ("Date", "datetime, timedelta, time"), ("django.utils", "timezone, termcolors, dateformat, translation."), ("django.conf", "settings"), ("%quickref", "Quick reference."), ("User", "Django Auth Model"), ("help", "Python's own help system."), ("object?", "Details about 'object'"), ("object??", "More Details about 'object' "), ] registered_models = {} for model in apps.get_models(): module = model.__module__ name = model.__name__ locals()[name] = model try: registered_models[module].append(name) except: registered_models[module] = [name] for module in registered_models: helpers.append((module, ", ".join(registered_models[module]))) banner2 = "\n".join([ "%s: %s" % (colorize(x, fg="yellow"), y) for x, y in helpers ]) + "\n" + colorize("RELOAD: \n %load_ext autoreload \n %autoreload", fg="red") + "\n" banner = "Hi! \n\n" \ "Here some useful shortcuts (Crtl-D to exit):" c = get_config() c.InteractiveShell.banner1 = banner c.InteractiveShell.banner2 = banner2 c.TerminalInteractiveShell.confirm_exit = False c.InteractiveShellApp.extensions = ['autoreload'] c.InteractiveShellApp.exec_lines = ['%autoreload 2', 'print 1asd'] rtx = embed(config=c)
def get_export_names(config=get_config()): """Return a list of the currently supported export targets Exporters can be found in external packages by registering them as an nbconvert.exporter entrypoint. """ exporters = sorted(entrypoints.get_group_named('nbconvert.exporters')) if os.environ.get("NBCONVERT_DISABLE_CONFIG_EXPORTERS"): get_logger().info( "Config exporter loading disabled, no additional exporters will be automatically included." ) return exporters enabled_exporters = [] for exporter_name in exporters: try: e = get_exporter(exporter_name)(config=config) if e.enabled: enabled_exporters.append(exporter_name) except (ExporterDisabledError, ValueError): pass return enabled_exporters
def test_bad_prefix(self): c = get_config() c.ReportCmd.raise_config_file_errors = True cmd = report.ReportCmd(config=c) arg = 'BAD_ARG' with self.assertRaisesRegexp(CmdException, re.escape("arg[1]: %s" % arg)): list(cmd.run(arg)) arg = 'inp:BAD_ARG' with self.assertRaisesRegexp(CmdException, re.escape("arg[1]: %s" % arg)): list(cmd.run(arg)) arg1 = 'inp:FOO' arg2 = 'out.BAR' with self.assertRaises(CmdException) as cm: list(cmd.run('inp=A', arg1, 'out=B', arg2)) #print(cm.exception) self.assertIn("arg[2]: %s" % arg1, str(cm.exception)) self.assertIn("arg[4]: %s" % arg2, str(cm.exception))
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 it"s configuration. This is useful for executing small snippets of management code without having to manually configuring the application. This code snippet is taken from Flask"s cli module and modified to run IPython and falls back to the normal shell if IPython is not available. """ import code banner = "Python %s on %s\nInstance Path: %s" % ( sys.version, sys.platform, current_app.instance_path, ) ctx = {"db": db} # 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(current_app.make_shell_context()) try: import IPython from traitlets.config import get_config c = get_config() # This makes the prompt to use colors again c.InteractiveShellEmbed.colors = "Linux" IPython.embed(config=c, banner1=banner, user_ns=ctx) except ImportError: code.interact(banner=banner, local=ctx)
def handle(self, *args, **options): User = get_user_model() helpers = [ ("Date", "datetime, timedelta, time"), ("django.utils", "timezone, termcolors, dateformat, translation."), ("%quickref", "Quick reference."), ("User", "Django Auth Model"), ("help", "Python's own help system."), ("object?", "Details about 'object'"), ("object??", "More Details about 'object' "), ] registered_models = {} for model in apps.get_models(): module = model.__module__ name = model.__name__ locals()[name] = model try: registered_models[module].append(name) except: registered_models[module] = [name] for module in registered_models: helpers.append((module, ", ".join(registered_models[module]))) banner2 = "\n".join(["%s: %s" % (colorize(x, fg="yellow"), y) for x, y in helpers]) + "\n" banner = "Hi! \n\n" \ "Here some useful shortcuts (Crtl-D to exit):" c = get_config() c.InteractiveShell.banner1 = banner c.InteractiveShell.banner2 = banner2 c.TerminalInteractiveShell.confirm_exit = False c.PromptManager.in_template = '$ ' c.PromptManager.out_template = '> ' embed(config=c)
def main(): args = read_args() # Handle shell extension commands try: if args.register: register_shell_extension('Open Sandboxed') register_shell_extension('Run Sandboxed', cli_flags='--run') return elif args.unregister: unregister_shell_extension('Open Sandboxed') unregister_shell_extension('Run Sandboxed') return except PermissionError: print("Try running again as an Administrator") return # Launch a new sandbox sandbox = winsandbox.new_sandbox(networking=args.interactive, virtual_gpu=not args.no_vgpu, logon_script=args.logon_script, folder_mappers=[ winsandbox.FolderMapper( folder_path=folder, read_only=False) for folder in args.folder ]) if args.interactive: config = get_config() config.InteractiveShellEmbed.colors = "Neutral" # Workaround to enable colors in embedded IPy. embed( config=config, header= 'Welcome to the Windows Sandbox!\nUse the `sandbox` object to control the sandbox.' )
def _config_default(self): return get_config()
def __init__(self, config=None): super(MetricaIdsMixin, self).__init__(config=get_config())
background_color = '#002b36' class SolarizedLight(Solarized): styles = {**solarized_common, **light} class SolarizedDark(Solarized): styles = {**solarized_common, **dark} def get_style_by_name(name, original=interactiveshell.get_style_by_name): if name.startswith('solarized'): return SolarizedDark if name.endswith('dark') else SolarizedLight else: return original(name) interactiveshell.get_style_by_name = get_style_by_name c = get_config() c.TerminalInteractiveShell.highlighting_style = 'solarized_dark' c.TerminalInteractiveShell.highlighting_style_overrides = { Token.Prompt: GREEN, Token.PromptNum: 'bold ' + GREEN, Token.OutPrompt: RED, Token.OutPromptNum: 'bold ' + RED, } c.TerminalInteractiveShell.true_color = True c.TerminalInteractiveShell.editing_mode = 'vi'