def cli(paths, mode, name_regex, pixel_size, dry_run, strict, name, mmap, lazy, no_show): """ PeepingTom command line interface. Opens files in napari and lands in an interactive ipython shell with peepingtom imported as `pt` and the initialised Peeper available as `p`. PATHS: any number of files or globs [default='./*'] \b MODE choices: - lone: each datablock in a separate volume - zip_by_type: one of each datablock type per volume - bunch: all datablocks in a single volume \b EXAMPLES: Open a .star file as particles: peep particles.star Open particles and images from a directory: peep /dir/with/star_and_mrc_files/ Match files such as MyProtein_10.star and MyProtein_001.mrc, and name the respective DataBlocks Protein_10 and Protein_001: peep /path/to/dir/MyProtein* -n 'Protein_\d+' """ # noqa: W605 if not paths: paths = ['./*'] if dry_run: files = pt.io_.find_files(paths) print('Files found:') print(*(str(file) for file in files), sep='\n') sys.exit() peeper = pt.read( *paths, # noqa: F841 name=name, mode=mode, name_regex=name_regex, pixel_size=pixel_size, strict=strict, mmap=mmap, lazy=lazy, ) # set up ipython shell nicely banner = '''=== PeepingTom === initialised variables: - peeper - viewer ''' sh = InteractiveShellEmbed(banner2=banner) sh.enable_gui('qt') sh.push('peeper') if not no_show: sh.run_cell('peeper.show()', silent=True) viewer = peeper.napari_viewer # noqa: F841 sh.push('viewer') sh()
def main(): parser = argparse.ArgumentParser() parser.add_argument('cmd', nargs='*', help='run this command and exit') args = parser.parse_args() c = Config() c.InteractiveShell.confirm_exit = False if args.cmd: c.PromptManager.out_template = '' c.HistoryAccessor.enabled = False ipshell = InteractiveShellEmbed(config=c, banner1='') ipshell.extension_manager.load_extension('xalc') if args.cmd: ipshell.run_cell(' '.join(args.cmd), store_history=False) sys.exit() print('xalc examples/tests:') for inp, out in tests: print(' {:10s} => {:10s}'.format(inp, out)) ipshell()
def run_cell(self, raw_cell, store_history=True, silent=False, shell_futures=True): """ run ipython code in ipython run_cell, run python console code in remoute console """ if self.redirect_to_ipython(raw_cell): return InteractiveShellEmbed.run_cell(self, raw_cell, store_history, silent, shell_futures) result = ExecutionResult() self.displayhook.exec_result = result if (not raw_cell) or raw_cell.isspace(): return result cell = self.ipython_pre_works(result, raw_cell, store_history, silent, shell_futures) output = self._runsource(cell) if output: result.result = output self._output(output) # self.write(output) self.ipython_post_works(result, store_history) return result
def cli(paths, mode, name_regex, pixel_size, dry_run, strict, name, lazy, no_show): """ Blik command line interface. Opens files in napari and lands in an interactive ipython shell with blik imported and the initialised DataSet available as `dataset`. PATHS: any number of files or globs [default='./*'] \b MODE choices: - lone: each datablock in a separate volume - zip_by_type: one of each datablock type per volume - bunch: all datablocks in a single volume \b EXAMPLES: Open a .star file as particles: blik particles.star Open particles and images from a directory: blik /dir/with/star_and_mrc_files/ Match files such as MyProtein_10.star and MyProtein_001.mrc, and name the respective DataBlocks Protein_10 and Protein_001: blik /path/to/dir/MyProtein* -n 'Protein_\d+' """ # noqa: W605 if not paths: paths = ['./*'] if dry_run: from blik.io_.reading.main import find_files files = [str(file) for file in find_files(paths)] if files: click.echo('Files found:\n' + '\n'.join(files)) else: click.echo('No files found.') click.get_current_context().exit() import blik from IPython.terminal.embed import InteractiveShellEmbed dataset = blik.read( *paths, # noqa: F841 name=name, mode=mode, name_regex=name_regex, pixel_size=pixel_size, strict=strict, lazy=lazy, ) # set up ipython shell nicely banner = '''=== Blik === initialised variables: - dataset - viewer ''' sh = InteractiveShellEmbed(banner2=banner) sh.enable_gui('qt') sh.push('dataset') if not no_show: sh.run_cell('dataset.show()', silent=True) viewer = dataset.napari_viewer # noqa: F841 sh.push('viewer') sh()
def main(): my_parser = argparse.ArgumentParser() my_parser.add_argument("-q", dest="quiet", default=False, action="store_true", help="be quiet [%(default)s]") my_parser.add_argument("--logger", type=str, default="stdout", choices=["stdout", "logserver"], help="choose logging facility [%(default)s]") my_parser.add_argument( "--logall", default=False, action="store_true", help="log all (no just warning / error), [%(default)s]") my_parser.add_argument("args", nargs=argparse.REMAINDER, help="commands to execute") opts = my_parser.parse_args() if opts.args: opts.quiet = True if not opts.quiet: print("Starting ICSW shell ... ", end="", flush=True) os.environ.setdefault("DJANGO_SETTINGS_MODULE", "initat.cluster.settings") try: import django if not opts.quiet: print("django.setup() ... ", end="", flush=True) django.setup() except: django = None else: from initat.cluster.backbone import db_tools try: if not db_tools.is_reachable(): django = None except: # when installing a newer icsw-client package on a machine with an old icsw-server package django = None from initat.icsw.magics import icsw_magics # First import the embeddable shell class from IPython.terminal.prompts import Prompts, Token from IPython.terminal.embed import InteractiveShellEmbed # Now create an instance of the embeddable shell. The first argument is a # string with options exactly as you would type them if you were starting # IPython at the system command line. Any parameters you want to define for # configuration can thus be specified here. ipshell = InteractiveShellEmbed(header="X", user_ns={"django": django}) class ICSWPrompt(Prompts): def in_prompt_tokens(self, cli=None): return [ (Token, "[CORVUS]"), (Token.Prompt, ">"), ] ipshell.prompts = ICSWPrompt(ipshell) ipshell.mouse_support = True ipshell.confirm_exit = False ipshell.autocall = 2 # no banner ipshell.banner1 = "" ipshell.set_hook('complete_command', icsw_magics.apt_completers, str_key='icsw') if False: class st2(object): def __dir__(self): return ["bla", "blo"] def abc(self, var): print("*", var) def _ipython_key_completions_(self): return ["x", "y"] def bla(self): return "bla" def __call__(self, *args): return "C", args xicsw = st2() def stest(sthg): print("stest:", sthg) ipshell.register_magics( icsw_magics.ICSWMagics(ipshell, True if django else False)) if opts.args: if "--" in opts.args: opts.args.remove("--") _args = ["icsw"] if opts.logall: _args.append("--logall") _args.append("--logger") _args.append(opts.logger) r = ipshell.run_cell(" ".join(_args + opts.args), silent=True) sys.exit(r.result) else: if not opts.quiet: print("done") from initat.cluster.backbone.models import device, device_group ipshell(header="Starting icsw", )
class TestIpython(unittest.TestCase): def setUp(self): self.ipshell = InteractiveShellEmbed() self.ipshell.run_cell('%load_ext sos_magic') def assertDictValue(self, key, value): self.ipshell.run_cell('__sos_dict__ = %sosdict') self.assertEqual(self.ipshell.user_ns['__sos_dict__'][key], value) def testSoSDict(self): '''Test sos dict magic''' self.ipshell.run_cell('%sosdict') self.ipshell.run_cell('keys = %sosdict --keys') # this make sure the symbols are imported for key in ['run', 'R', 'bash', 'python', 'sos_variable']: self.assertTrue(key not in self.ipshell.user_ns['keys']) # self.ipshell.run_cell('keys = %sosdict --keys --all') # this make sure the symbols are imported for key in ['run', 'R', 'bash', 'python', 'sos_variable']: self.assertTrue(key in self.ipshell.user_ns['keys']) # # add something self.ipshell.run_cell('%sos a=1') self.assertDictValue('a', 1) # # reset self.ipshell.run_cell('%sosdict --reset') self.ipshell.run_cell('__sos_dict__ = %sosdict') self.assertTrue('a' not in self.ipshell.user_ns['__sos_dict__']) def testSoS(self): '''Test magic %sos''' self.ipshell.run_cell('''%sos a=10''') self.ipshell.run_cell('''%sos b=['file1.txt', 'file2.txt']''') self.ipshell.run_cell('''%sos c="${b!r,}" ''') self.assertDictValue('a', 10) self.assertDictValue('b', ['file1.txt', 'file2.txt']) self.assertDictValue('c', "'file1.txt', 'file2.txt'") def testSet(self): '''test %sosset''' self.ipshell.run_cell('''%sosset --rep 3''') self.ipshell.run_cell('''%%sos parameter: rep = 5 ''') self.assertDictValue('rep', 3) def testSoSPut(self): '''test %put''' self.ipshell.run_cell('a = 12345') self.ipshell.run_cell('b = "12345"') self.ipshell.run_cell('%sosput a b') self.assertDictValue('a', 12345) self.assertDictValue('b', "12345") def testSoSGet(self): '''test %get''' self.ipshell.run_cell('%sos a = 12345') self.ipshell.run_cell('%sos b = "12345"') self.ipshell.run_cell('%sosget a b') self.assertEqual(self.ipshell.user_ns['a'], 12345) self.assertEqual(self.ipshell.user_ns['b'], "12345")