def shell(ipython): """Runs a Python shell with QPD context""" import code import readline import rlcompleter banner_msg = ( "Welcome to QPD interactive shell\n" "\tAuto imported: app, db, models, views, admin" ) _vars = globals() _vars.update(locals()) _vars.update(dict(app=app, db=db, models=models, views=views, admin=admin)) readline.set_completer(rlcompleter.Completer(_vars).complete) readline.parse_and_bind("tab: complete") try: if ipython is True: from IPython import start_ipython from traitlets.config import Config c = Config() c.TerminalInteractiveShell.banner2 = banner_msg start_ipython(argv=[], user_ns=_vars, config=c) else: raise ImportError except ImportError: shell = code.InteractiveConsole(_vars) shell.interact(banner=banner_msg)
def run(self, loc): start_ipython(argv=[], user_ns=loc, config=cfg, banner1="[+] launching interactive shell", exit_msg="[+] interactive shell terminating") return 0
def main(): parser = argparse.ArgumentParser(description='image viewer') parser.add_argument('image', help='path to the image') parser.add_argument('--interactive', '-i', action='store_true', help='start an interactive shell') opts = parser.parse_args() input_image = opts.image image = QtGui.QImage() image.load(input_image) app = QtWidgets.QApplication(sys.argv) try: import signal signal.signal(signal.SIGINT, sigint_handler) except ImportError: pass window = ImageViewerWindow(image, input_image) window.show() if opts.interactive: global main_loop_type main_loop_type = 'ipython' from IPython import start_ipython start_ipython(user_ns=dict(globals(), **locals()), argv=[]) else: app.exec_()
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 shell(ipython): """Runs a Python shell with Robottelo context""" _vars = globals() _vars.update(locals()) auto_imported = { 'settings': settings, 'entities': nailgun.entities, 'ng': nailgun, 'rt': RobotteloLoader() } _vars.update(auto_imported) banner_msg = ( 'Welcome to Robottelo interactive shell\n' '\tAuto imported: {0}\n' '\tng is nailgun e.g: ng.client\n' '\trt is robottelo e.g: rt.datafactory\n' ).format(auto_imported.keys()) readline.set_completer(rlcompleter.Completer(_vars).complete) readline.parse_and_bind('tab: complete') try: if ipython is True: from IPython import start_ipython from traitlets.config import Config c = Config() c.TerminalInteractiveShell.banner2 = banner_msg start_ipython(argv=[], user_ns=_vars, config=c) else: raise ImportError except ImportError: shell = code.InteractiveConsole(_vars) shell.interact(banner=banner_msg)
def IPythonShell(namespace, banner): from IPython import start_ipython sys.argv = [''] # This is needed because argparse tries to grab argv[0] from IPython.config import Config c = Config() c.TerminalInteractiveShell.banner1 = banner start_ipython(user_ns=namespace, argv=[], config=c)
def main(): import argparse, errno, sys parser = argparse.ArgumentParser(description='image viewer') parser.add_argument('inputs', type=str, nargs=1, help='path to the image') parser.add_argument('--interactive', '-i', action='store_true', help='launch in interactive shell') opts = parser.parse_args() input_image = opts.inputs[0] image = QImage() image.load(input_image) app = QApplication(sys.argv) try: import signal signal.signal(signal.SIGINT, sigint_handler) except ImportError: pass window = ImageViewerWindow(image, input_image) window.show() if opts.interactive: global main_loop_type main_loop_type = 'ipython' from IPython import start_ipython start_ipython(user_ns=dict(globals(), **locals()), argv=[]) else: app.exec_()
def start_ipython_shell(verbose): from IPython.terminal.interactiveshell import InteractiveShell as Shell from IPython import start_ipython Shell.banner = BANNER namespace = start_shell_namespace(os.getcwd(), verbose) exec('from kpop.all import *', namespace) start_ipython(user_ns=namespace, argv=[])
def shell(ctx): """ IPython shell """ from IPython import start_ipython start_ipython(argv=[])
def ipython(**locals_): # pylint: disable-all 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 start_shell(): try: from IPython import start_ipython start_ipython(argv=[], user_ns=load_user_ns()) except ImportError: print "Install IPython to get it works." else: print "Interactive shell exit successfully."
def IPythonShell(namespace, banner): from IPython import start_ipython sys.argv = ['' ] # This is needed because argparse tries to grab argv[0] from IPython.config import Config c = Config() c.TerminalInteractiveShell.banner1 = banner start_ipython(user_ns=namespace, argv=[], config=c)
def shell(): """Abre um shell com o objeto app no contexto""" with app.app_context(): try: from IPython import start_ipython start_ipython(argv=[], user_ns={'app': app}) except: code.interact(banner='Meu Candidato', local={'app': app})
def shell_command(): ctx = current_app.make_shell_context() try: from IPython import start_ipython start_ipython(argv=(), user_ns=ctx) except ImportError: from code import interact interact(local=ctx)
def shell(): """Open a shell with app in the context""" with app.app_context(): try: from IPython import start_ipython start_ipython(argv=[], user_ns={'app': app}) except: code.interact(banner='Busca Bike', local={'app': app})
def shell(ctx): """ IPython shell """ from IPython import start_ipython start_ipython(argv=[], extensions=['asynciomagic'])
def shell(ipython, _settingspath): # pragma: no cover """Run a Python shell with Pulp-Smash context. Start an interactive shell with pulp-smash objects available, if `ipython` is installed it will start ipython session, else it will start standard python shell. """ # pylint:disable=R0914 import code import rlcompleter # trick to to make subpackages available from pulp_smash import ( # noqa: F401 api, cli, utils, pulp2, pulp3, constants, ) from pulp_smash.pulp2 import constants as pulp2_constants # noqa: F401 from pulp_smash.pulp3 import constants as pulp3_constants # noqa: F401 from pulp_smash.pulp2 import utils as pulp2_utils # noqa: F401 from pulp_smash.pulp3 import utils as pulp3_utils # noqa: F401 banner_msg = ( "Welcome to Pulp-Smash interactive shell\n" "\tAuto imported: api, cli, config, utils, pulp2, pulp3, constants, " "exceptions\n") _vars = globals() try: cfg = config.get_config() except exceptions.ConfigFileNotFoundError as exc: warnings.warn(str(exc)) cfg = "Please create your instance of cfg or set the settings location" else: api.client = api.Client(cfg) cli.client = cli.Client(cfg) banner_msg += "\tAvailable objects: api.client, cli.client, cfg\n" finally: _vars.update(locals()) with contextlib.suppress(ImportError): import readline readline.set_completer(rlcompleter.Completer(_vars).complete) readline.parse_and_bind("tab: complete") try: if ipython is True: from IPython import start_ipython from traitlets.config import Config conf = Config() conf.TerminalInteractiveShell.banner2 = banner_msg start_ipython(argv=[], user_ns=_vars, config=conf) else: raise ImportError except ImportError: if ipython is True: warnings.warn("Cannot load ipython, please `pip install ipython`") _shell = code.InteractiveConsole(_vars) _shell.interact(banner=banner_msg)
def create_shell(console, manage_dict=None, extra_vars=None): """Creates the shell""" manage_dict = manage_dict or MANAGE_DICT _vars = globals() _vars.update(locals()) auto_imported = import_objects(manage_dict) if extra_vars: auto_imported.update(extra_vars) _vars.update(auto_imported) msgs = [] if manage_dict['shell']['banner']['enabled']: msgs.append( manage_dict['shell']['banner']['message'].format(**manage_dict)) if auto_imported and manage_dict['shell']['auto_import']['display']: auto_imported_names = [ key for key in auto_imported.keys() if key not in ['__builtins__', 'builtins'] ] msgs.append('\tAuto imported: {0}\n'.format(auto_imported_names)) banner_msg = u'\n'.join(msgs) exec_init(manage_dict, _vars) exec_init_script(manage_dict, _vars) if console == 'ptpython': try: from ptpython.repl import embed embed({}, _vars) except ImportError: click.echo("ptpython is not installed!") return if console == 'bpython': try: from bpython import embed embed(locals_=_vars, banner=banner_msg) except ImportError: click.echo("bpython is not installed!") return try: if console == 'ipython': from IPython import start_ipython from traitlets.config import Config c = Config() c.TerminalInteractiveShell.banner2 = banner_msg start_ipython(argv=[], user_ns=_vars, config=c) else: raise ImportError except ImportError: if manage_dict['shell']['readline_enabled']: import readline import rlcompleter readline.set_completer(rlcompleter.Completer(_vars).complete) readline.parse_and_bind('tab: complete') shell = code.InteractiveConsole(_vars) shell.interact(banner=banner_msg)
def shell(): from IPython import start_ipython from IPython.terminal.ipapp import load_default_config c = load_default_config() c.TerminalIPythonApp.display_banner = False c.TerminalInteractiveShell.confirm_exit = False c.InteractiveShellApp.exec_lines = EXEC_LINES start_ipython(argv=(), config=c)
def entry(): namespace={} exec('from spock import *', namespace) print 'publishing these names: ', namespace.keys() try: from IPython import start_ipython start_ipython(user_ns=namespace) except ImportError: raise SystemExit("ERROR: spock's shell requires IPython to be installed.")
def main(argv): parser = ArgumentParser(prog="bootstrap", usage="./bootstrap.py <script>", description=__doc__) parser.add_argument("script", nargs="*") parser.add_argument( "-m", help="run library module as a script (terminates option list)") Options = collections.namedtuple("Options", ["script", "module"]) if len(argv) == 1: options = Options(script=None, module=None) else: if argv[1] in ["-h", "--help"]: parser.print_help() return if argv[1] == "-m": if len(argv) < 3: parser.parse_args(argv[1:]) return options = Options(script=None, module=argv[2:]) else: options = Options(script=argv[1:], module=None) if options.script is not None: logger.info("Executing %s from source checkout", options.script) script = options.script[0] argv = options.script[1:] kind, target = find_executable(script) if kind == "path": run_file(target, argv) elif kind == "entry_point": run_entry_point(target, argv) else: logger.error("Script %s not found", options.script) elif options.module is not None: logging.info("Running module %s", options.module) import runpy module = options.module[0] try: old = sys.argv sys.argv = [None] + options.module[1:] runpy.run_module(module, run_name="__main__", alter_sys=True) finally: sys.argv = old else: logging.info("Running IPython by default") logger.info("Patch the sys.argv: %s", sys.argv) sys.path.insert(2, "") try: from IPython import start_ipython except Exception as err: logger.error("Unable to execute iPython, using normal Python") logger.error(err) import code code.interact() else: start_ipython(argv=[])
def _ipython(self): """Start IPython >= 1.0""" from IPython import start_ipython user_ns = self.get_start_namespace() if user_ns: start_ipython(argv=[], user_ns=user_ns) else: start_ipython(argv=[])
def _ipython(): """Start IPython >= 1.0""" from IPython import start_ipython # pylint: disable=import-error,no-name-in-module user_ns = get_start_namespace() if user_ns: start_ipython(argv=[], user_ns=user_ns) else: start_ipython(argv=[])
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 console_msg(self, msg): if msg['status'] == "ok": shell = msg['shell'] if shell: from IPython import start_ipython start_ipython(['console', '--existing', shell]) return '' else: msg['reason'] = 'Could not start ipython kernel' return self.console_error(msg)
def main(args): client = MongoClient(args.url) db = client[args.db_name] try: from IPython import start_ipython start_ipython(argv=[], user_ns=dict(db=db)) except ImportError: import code shell = code.InteractiveConsole(dict(db=db)) shell.interact()
def interactive(self): local_vars = {"analyse": self} try: from IPython import start_ipython start_ipython(argv=[], user_ns=local_vars) except ImportError: from code import interact banner = ["%s: %s" % pair for pair in sorted(local_vars.items())] interact("\n".join(banner), local=local_vars)
def start_undoable_ipython(args=None): """Start an undoable instance of ipython. Args: args: Arguments passed to the undoable instance to be started. """ patch_ipython() if args: sys.argv = args start_ipython()
def start(*args): conf = parser.parse_args(args) if len(args) > 0 else parser.parse_args() if conf.conf is not None: os.environ['VACA_CONNECTION_CONFIG'] = conf.conf if conf.connection is not None: os.environ['VACA_DEFAULT_CONNECTION'] = conf.connection p = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) os.environ['PYTHONSTARTUP'] = os.path.join(p, 'vaca', 'ipython_config.py') start_ipython([])
def pyinvoke(args=None): try: from IPython import start_ipython except ImportError: print(red('Import is not installed. Type "pip install ipython"')) else: start_ipython(argv=[], user_ns={ 'DB': DB, 'config': config, 'get_document': get_document })
def main(args): pass url = os.environ['SACRED_MONGO_URL'] db_name = os.environ['SACRED_DB_NAME'] client = MongoClient(url) db = client[db_name] try: from IPython import start_ipython start_ipython(argv=[], user_ns=dict(db=db)) except ImportError: import code shell = code.InteractiveConsole(dict(db=db)) shell.interact()
def start_notebook(working_dir=None): ''' Inicia el jupyter notebook in working_directory :param working_dir: Directorio de arranque para el jupyter notebook :return: None ''' working_dir = working_dir or os.path.dirname(__file__) os.chdir(working_dir) start_ipython([ 'notebook', '--no-browser', ])
def run(self): if not self.manager.args.no_model: exec ('from %s import *' % settings.MODELS_MODULE) try: from IPython import start_ipython start_ipython(argv=[], user_ns=locals()) except: import readline import code vars = globals().copy() vars.update(locals()) shell = code.InteractiveConsole(vars) shell.interact()
def shell(ctx): """ IPython shell :param ctx: :return: """ from IPython import start_ipython # Preloading 'asynciomagic' extension for using directive %%async_ # Example: # %%async_ await func() start_ipython(argv=[], extensions=['asynciomagic'])
def run(self): if not self.manager.args.no_model: exec('from %s import *' % settings.MODELS_MODULE) try: from IPython import start_ipython start_ipython(argv=[], user_ns=locals()) except: import readline import code vars = globals().copy() vars.update(locals()) shell = code.InteractiveConsole(vars) shell.interact()
def mongo(): """Start an IPython/Python shell for interacting with Sacred's mongodb.""" url = os.environ['SACRED_MONGO_URL'] db_name = os.environ['SACRED_DB_NAME'] client = MongoClient(url) db = client[db_name] try: from IPython import start_ipython start_ipython(argv=[], user_ns=dict(db=db)) except ImportError: import code shell = code.InteractiveConsole(dict(db=db)) shell.interact()
def ipython(): '''Configuration for IPython ''' # Line which must be appended to IPython config config_line = '''c.InteractiveShellApp.extensions = ['pdflatex_magic', 'bash2_magic']''' # Location of IPython default profile try: profile = locate_profile() except (ProfileDirError, OSError): start_ipython(argv=['profile', 'create', 'default']) profile = locate_profile() # Append extensions line to end of profile config config_file = os.path.join(profile, 'ipython_config.py') # Open config file fh = open(config_file, 'r+') # Search for line to be configured # Ensure it isn't a comment line_list = [] for line in fh.readlines(): if 'c.InteractiveShellApp.extensions' in line: if not line.lstrip().startswith('#'): line_list.append(line) # There should be at most one, othewise config is broken # If config is broken, this won't break it more :-P if len(line_list) == 1: # Extract current extensions before = line_list[0].split('[') after = before[1].split(']') # If none, just put new ones straight it if after[0].strip() == '': after[0] = "'pdflatex_magic', 'bash2_magic'" else: if "'pdflatex_magic'" not in after[0]: after[0] += ", 'pdflatex_magic'" if "'bash2_magic'" not in after[0]: after[0] += ", 'bash2_magic'" config_line = before[0] + '[' + ']'.join(after) fh.close() # To substitute into existing file we need to create a copy replace(config_file, line_list[0], config_line) else: # Write config line to file (at the end) fh.writelines(config_line) fh.close()
def main(args): # Get genes and file paths names = pd.read_pickle(STRUCTURES) # We don't need the SCOP data: names = names.groupby(level='name').head(1) names = names.drop(columns=['domain']) # Will's enrichment data enrichment = pd.read_pickle(ENRICHMENT) # Now, Will used different names sometimes # in particular, we want to change # 'bioD' -> 'bioD1' # 'umpH' -> 'nagD' enrichment = enrichment.set_index("name", drop=False) enrichment.loc['bioD', "name"] = 'bioD1' enrichment.loc['umpH', "name"] = 'nagD' # Sometimes Will used different gene names names['all_names'] = [ [name] + synonyms for name, synonyms in zip(names['name'], names['synonyms']) ] expanded = expand_df(names, 'all_names') expanded = expanded.set_index(["all_names", "name"], drop=False) # Now for some reason, there are duplicates due to synonyms # I'm going to take care of the 2 that conflict # fabG, mgsA expanded = expanded.drop([('fabG', 'accC'), ('mgsA', 'rarA')]) # Keep only those with enrichment data will_gene_names = [s.lower() for s in enrichment['name'].unique()] has_enrichment = [ name.lower() in will_gene_names for name in expanded.index.get_level_values('all_names') ] expanded = expanded[has_enrichment].copy() # At 511 genes, exactly the number will has expanded["locations"] = expanded["all_names"].apply( find_enriched_regions, args=(enrichment, args.enrichment_threshold, args.pvalue_threshold), excluded_length=args.nterm_exclusion) # Note that these are locations along the gene sequence # Whatever further analysis: if args.ipython: sys.argv = [sys.argv[0]] start_ipython(user_ns=dict(locals(), **globals())) return 0
def main(args): # Build up gene dataframe with open(args.cds_file) as f: genes = SeqIO.parse(f, "fasta") gather = collections.defaultdict(list) for gene in genes: annotations = parse_description(gene.description) if 'protein_id' not in annotations: if annotations['pseudo'] != "true": print(gene.description) continue gather['name'].append(annotations['gene']) gather['bnum'].append(annotations['locus_tag']) gather['xref'].append(annotations['db_xref']) gather['description'].append(annotations['protein']) gather['accession'].append(annotations['protein_id']) gather['seq'].append(str(gene.seq)) df_genes = pd.DataFrame(gather) df_genes = df_genes.set_index("accession") print("Genes have been read. Number:", len(df_genes)) # Build protein dataframe to with aa sequences with open(args.translated_file) as f: proteins = SeqIO.parse(f, "fasta") gather = collections.defaultdict(list) for protein in proteins: annotations = parse_description(protein.description) if 'protein_id' not in annotations: continue # gather['name'].append(annotations['gene']) gather['accession'].append(annotations['protein_id']) gather['aaseq'].append(str(protein.seq)) df_proteins = pd.DataFrame(gather) df_proteins = df_proteins.set_index("accession") print("CDS have been read. Number:", len(df_proteins)) merged = pd.merge(df_genes, df_proteins, on='accession') print("Genes and CDS matched. Number:", len(merged)) # I found that inner, left, or right join will yield the same result # 4242 genes # I also confirmed that all aa sequences match the length of # corresponding nucleotide sequences (3*aa_len + 3). merged.to_pickle("1_genes.pkl") print("Dataframe saved.") if args.ipython: sys.argv = [sys.argv[0]] start_ipython(user_ns=dict(locals(), **globals())) return
def interactive_shell(self): self.confirm = yes self.need_wrap = False # avoid '_' to be added to builtins by sys.display_hook def do_not_add___to_builtins(obj): if obj is not None: print(repr(obj)) sys.displayhook = do_not_add___to_builtins local_ctx = self._create_context() try: import readline from cubicweb.toolsutils import CWShellCompleter except ImportError: # readline not available pass else: rql_completer = CWShellCompleter(local_ctx) readline.set_completer(rql_completer.complete) readline.parse_and_bind('tab: complete') home_key = 'HOME' if sys.platform == 'win32': home_key = 'USERPROFILE' histfile = os.path.join(os.environ[home_key], ".cwshell_history") try: readline.read_history_file(histfile) except IOError: pass from code import interact banner = """entering the migration python shell just type migration commands or arbitrary python code and type ENTER to execute it type "exit" or Ctrl-D to quit the shell and resume operation""" # use ipython if available try: from IPython import start_ipython print(banner) start_ipython(argv=[], user_ns=local_ctx) except ImportError: interact(banner, local=local_ctx) try: readline.write_history_file(histfile) except IOError: pass # delete instance's confirm attribute to avoid questions del self.confirm self.need_wrap = True
def create_shell(ipython, ptpython, manage_dict=None, extra_vars=None): """Creates the shell""" manage_dict = manage_dict or MANAGE_DICT _vars = globals() _vars.update(locals()) auto_imported = import_objects(manage_dict) if extra_vars: auto_imported.update(extra_vars) _vars.update(auto_imported) msgs = [] if manage_dict['shell']['banner']['enabled']: msgs.append( manage_dict['shell']['banner']['message'].format(**manage_dict) ) if auto_imported and manage_dict['shell']['auto_import']['display']: auto_imported_names = [ key for key in auto_imported.keys() if key not in ['__builtins__', 'builtins'] ] msgs.append('\tAuto imported: {0}\n'.format(auto_imported_names)) banner_msg = u'\n'.join(msgs) if manage_dict['shell']['readline_enabled']: readline.set_completer(rlcompleter.Completer(_vars).complete) readline.parse_and_bind('tab: complete') exec_init(manage_dict, _vars) exec_init_script(manage_dict, _vars) if ptpython: try: from ptpython.repl import embed embed({}, _vars) except ImportError: click.echo("ptpython is not installed!") return try: if ipython is True: from IPython import start_ipython from traitlets.config import Config c = Config() c.TerminalInteractiveShell.banner2 = banner_msg start_ipython(argv=[], user_ns=_vars, config=c) else: raise ImportError except ImportError: shell = code.InteractiveConsole(_vars) shell.interact(banner=banner_msg)
def run_cli(): from multiprocessing import freeze_support freeze_support() setup_logging() # Use default matplotlib backend on mac/linux, but wx on windows. # The problem on mac is that the wx backend requires pythonw. On windows # we are sure to wx since it is the shipped with the app. setup_mpl(backend='WXAgg' if os.name == 'nt' else None) setup_sasmodels() if len(sys.argv) == 1 or sys.argv[1] == '-i': # Run sasview as an interactive python interpreter try: from IPython import start_ipython sys.argv = ["ipython", "--pylab"] sys.exit(start_ipython()) except ImportError: import code code.interact(local={'exit': sys.exit}) elif sys.argv[1] == '-c': exec(sys.argv[2]) else: thing_to_run = sys.argv[1] sys.argv = sys.argv[1:] import runpy if os.path.exists(thing_to_run): runpy.run_path(thing_to_run, run_name="__main__") else: runpy.run_module(thing_to_run, run_name="__main__")
def start(self) -> None: try: from IPython import start_ipython from IPython.utils import io from traitlets.config.loader import Config as IPyConfig except ImportError: raise ShellNotAvailableError( "IPython shell not available " "or IPython version not supported." ) # Hack to show custom banner # TerminalIPythonApp/start_app doesn't allow you to customize the # banner directly, so we write it to stdout before starting the IPython app io.stdout.write(self.banner) # Pass exec_lines in order to start autoreload if self.ipy_autoreload: if not isinstance(self.ipy_autoreload, bool): mode = self.ipy_autoreload else: mode = 2 logger.debug(f"Initializing IPython autoreload in mode {mode}") exec_lines = [ "import konch as __konch", f"__konch.IPythonShell.init_autoreload({mode})", ] else: exec_lines = [] ipy_config = IPyConfig() if self.ipy_colors: ipy_config.TerminalInteractiveShell.colors = self.ipy_colors if self.ipy_highlighting_style: ipy_config.TerminalInteractiveShell.highlighting_style = ( self.ipy_highlighting_style ) configure_ipython_prompt(ipy_config, prompt=self.prompt, output=self.output) # Use start_ipython rather than embed so that IPython is loaded in the "normal" # way. See https://github.com/django/django/pull/512 start_ipython( display_banner=False, user_ns=self.context, config=ipy_config, extensions=self.ipy_extensions or [], exec_lines=exec_lines, argv=[], ) return None
def shell(ipython): """Runs a Python shell with Quokka context""" import code import readline import rlcompleter _vars = globals() _vars.update(locals()) _vars.update(dict(app=app, db=db)) readline.set_completer(rlcompleter.Completer(_vars).complete) readline.parse_and_bind("tab: complete") try: if ipython is True: from IPython import start_ipython start_ipython(argv=[], user_ns=_vars) else: raise ImportError except ImportError: shell = code.InteractiveConsole(_vars) shell.interact()
def parse_args_and_run(): parser = argparse.ArgumentParser() parser.add_argument('-v', '--version', action='store_true', help='Display the version number of okcupyd') util.add_command_line_options(parser.add_argument) args = parser.parse_args() if args.version: print(pkg_resources.get_distribution('okcupyd').version) sys.exit() util.handle_command_line_options(args) util.get_credentials() sys.exit(start_ipython(['-i', os.path.join(os.path.dirname(__file__), 'start.py')]))
def do_shell(self, line): """Open a IPython CAM shell. the kat object will be there and ready. """ cam = False controlled_clients = False for segment in [s.lower() for s in line.split()]: if segment == 'cam': cam = getpass.getpass("CAM Password or ENTER to continue:") # cam_pass='******' cam = cam.strip() if not cam: cam = True elif segment == 'all': controlled_clients = 'all' import IPython from IPython import start_ipython try: # New IPython c = IPython.config.application.get_config() except AttributeError: # Old IPython c = IPython.config.loader.Config() # Set the configuration of the IPython session: # https://ipython.org/ipython-doc/dev/config/intro.html c.TerminalIPythonApp.display_banner = True c.InteractiveShellApp.exec_lines = ['import katuilib'] if cam is False: c.InteractiveShellApp.exec_lines.append('configure()') elif cam is True: c.InteractiveShellApp.exec_lines.append('configure_cam()') else: cmd = 'configure_cam(' cmd += 'cam_pass="******"'.format(cam) if controlled_clients: cmd += ", controlled_clients='all'" cmd += ')' c.InteractiveShellApp.exec_lines.append(cmd) start_ipython(argv=[], config=c)
def shell(argparse, cmd, args): # pragma: no cover """ Start an interactive IPython shell with pwny imported globally. """ import pwny from IPython import start_ipython from IPython.config import get_config pwny_locals = dict( (key, getattr(pwny, key)) for key in dir(pwny) if not key.startswith('__') and not key == 'shell' ) config = get_config() config.InteractiveShell.confirm_exit = False start_ipython( argv=args, config=config, user_ns=pwny_locals, )
def run_manual(kwik_path, clustering=None, interactive=False, cluster_ids=None): import phy from phy.cluster import Session from phy.gui import start_qt_app, run_qt_app if not op.exists(kwik_path): print("The file `{}` doesn't exist.".format(kwik_path)) return 1 print("\nLoading {}...".format(kwik_path)) session = Session(kwik_path, clustering=clustering, ) print("Data successfully loaded!\n") session.model.describe() start_qt_app() gui = session.show_gui(cluster_ids=cluster_ids, show=False) print("\nPress `ctrl+h` to see the list of keyboard shortcuts.\n") # Interactive mode with IPython. if interactive: print("\nStarting IPython...") from IPython import start_ipython # Namespace. ns = {'phy': phy, 'session': session, 'model': session.model, 'kwik_path': kwik_path, 'gui': gui, } start_ipython(["--gui=qt", "-i", "-c='gui.show()'"], user_ns=ns) else: gui.show() run_qt_app()
def _run_cmd(cmd, ctx, glob, loc): # pragma: no cover """Run a command with optionally a debugger, IPython, or profiling.""" if PDB: _enable_pdb() if IPYTHON: from IPython import start_ipython args_ipy = ['-i', '--gui=qt'] ns = glob.copy() ns.update(loc) return start_ipython(args_ipy, user_ns=ns) # Profiling. The builtin `profile` is added in __init__. prof = __builtins__.get('profile', None) if prof: prof = __builtins__['profile'] return _profile(prof, cmd, glob, loc) return exec_(cmd, glob, loc)
def run_cli(): setup_mpl() if len(sys.argv) == 1: # Run sasview as an interactive python interpreter sys.argv = ["ipython", "--pylab"] from IPython import start_ipython sys.exit(start_ipython()) else: # Run sasview as a python script interpreter ## Run sasview as an interactive python interpreter # if sys.argv[1] == "-i": # sys.argv = ["ipython", "--pylab"] # from IPython import start_ipython # sys.exit(start_ipython()) thing_to_run = sys.argv[1] sys.argv = sys.argv[1:] import runpy if os.path.exists(thing_to_run): runpy.run_path(thing_to_run, run_name="__main__") else: runpy.run_module(thing_to_run, run_name="__main__")
def main(): cmd = """import seamless from seamless import context, cell, pythoncell, transformer, reactor, \ macro, export from seamless.lib import link, edit, display from seamless.gui import shell """ if len(sys.argv) == 1: cmd += "ctx = context()" else: assert len(sys.argv) == 2 # syntax: seamless file.seamless f = sys.argv[1] if f.endswith(".seamless"): cmd += "ctx = seamless.fromfile('{0}')".format(f) else: cmd += "ctx = context()\n" cmd += "__file__ = '{0}'\n".format(f) cmd += open(f).read() sys.argv = [sys.argv[0], "-c", cmd, "-i"] from IPython import start_ipython sys.exit(start_ipython())
def main(): """ Run the bumps program with the command line interface. Input parameters are taken from sys.argv. """ # add full traceback to warnings #warnings.showwarning = warn_with_traceback if len(sys.argv) == 1: sys.argv.append("-?") print("\nNo modelfile parameter was specified.\n") # run command with bumps in the environment if sys.argv[1] == '-m': import runpy sys.argv = sys.argv[2:] runpy.run_module(sys.argv[0], run_name="__main__") sys.exit() elif sys.argv[1] == '-p': import runpy sys.argv = sys.argv[2:] runpy.run_path(sys.argv[0], run_name="__main__") sys.exit() elif sys.argv[1] == '-c': run_command(sys.argv[2]) sys.exit() elif sys.argv[1] == '-i': sys.argv = ["ipython", "--pylab"] from IPython import start_ipython sys.exit(start_ipython()) opts = options.getopts() setup_logging() if opts.edit: from .gui.gui_app import main as gui gui() return # Set up the matplotlib backend to minimize the wx/gui dependency. # If no GUI specified and not editing, then use the default mpl # backend for the python version. if opts.batch or opts.remote or opts.noshow: # no interactivity config_matplotlib(backend='Agg') else: # let preview use default graphs config_matplotlib() problem = initial_model(opts) # TODO: AMQP mapper as implemented requires workers started up with # the particular problem; need to be able to transport the problem # to the worker instead. Until that happens, the GUI shouldn't use # the AMQP mapper. if opts.mpi: MPIMapper.start_worker(problem) mapper = MPIMapper elif opts.parallel or opts.worker: if opts.transport == 'amqp': mapper = AMQPMapper elif opts.transport == 'mp': mapper = MPMapper elif opts.transport == 'celery': mapper = CeleryMapper else: raise ValueError("unknown mapper") else: mapper = SerialMapper if opts.worker: mapper.start_worker(problem) return if np.isfinite(float(opts.time)): import time start_time = time.time() stop_time = start_time + float(opts.time)*3600 abort_test=lambda: time.time() >= stop_time else: abort_test=lambda: False fitdriver = FitDriver( opts.fit_config.selected_fitter, problem=problem, abort_test=abort_test, **opts.fit_config.selected_values) if opts.time_model: run_timer(mapper.start_mapper(problem, opts.args), problem, steps=int(opts.steps)) elif opts.profile: run_profiler(problem, steps=int(opts.steps)) elif opts.chisq: if opts.cov: print(problem.cov()) print("chisq", problem.chisq_str()) elif opts.preview: if opts.cov: print(problem.cov()) preview(problem) elif opts.resynth > 0: resynth(fitdriver, problem, mapper, opts) elif opts.remote: # Check that problem runs before submitting it remotely chisq = problem() print("initial chisq:", chisq) job = start_remote_fit(problem, opts, queue=opts.queue, notify=opts.notify) print("remote job:", job['id']) else: if opts.resume: resume_path = os.path.join(opts.resume, problem.name) else: resume_path = None make_store(problem, opts, exists_handler=store_overwrite_query) # Show command line arguments and initial model print("#", " ".join(sys.argv)) problem.show() if opts.stepmon: fid = open(problem.output_path + '.log', 'w') fitdriver.monitors = [ConsoleMonitor(problem), StepMonitor(problem, fid, fields=['step', 'value'])] #import time; t0=time.clock() fitdriver.mapper = mapper.start_mapper(problem, opts.args) best, fbest = fitdriver.fit(resume=resume_path) # print("time=%g"%(time.clock()-t0),file=sys.__stdout__) save_best(fitdriver, problem, best) if opts.err or opts.cov: fitdriver.show_err() if opts.cov: np.set_printoptions(linewidth=1000000) print("=== Covariance matrix ===") print(problem.cov()) print("=========================") if opts.entropy: print("Calculating entropy...") S, dS = fitdriver.entropy() print("Entropy: %s bits" % format_uncertainty(S, dS)) mapper.stop_mapper(fitdriver.mapper) if not opts.batch and not opts.mpi and not opts.noshow: beep() import pylab pylab.show()
# starting IPython using Python code from IPython import start_ipython start_ipython()
def go(): parser = argparse.ArgumentParser() util.add_command_line_options(parser.add_argument) util.handle_command_line_options(parser.parse_args()) util.get_credentials() sys.exit(start_ipython(['-i', os.path.join(os.path.dirname(__file__), 'start.py')]))
def _ipython(self): from IPython import start_ipython start_ipython(argv=[], user_ns=self.locals)
def ipython(self, local_vars): from IPython import start_ipython start_ipython(argv=[], user_ns=local_vars)