def load(self, arg_s): """Load code into the current frontend. Usage:\\ %load [options] source where source can be a filename, URL, input history range, macro, or element in the user namespace Options: -r <lines>: Specify lines or ranges of lines to load from the source. Ranges could be specified as x-y (x..y) or in python-style x:y (x..(y-1)). Both limits x and y can be left blank (meaning the beginning and end of the file, respectively). -s <symbols>: Specify function or classes to load from python source. -y : Don't ask confirmation for loading source above 200 000 characters. -n : Include the user's namespace when searching for source code. This magic command can either take a local filename, a URL, an history range (see %history) or a macro as argument, it will prompt for confirmation before loading source with more than 200 000 characters, unless -y flag is passed or if the frontend does not support raw_input:: %load myscript.py %load 7-27 %load myMacro %load http://www.example.com/myscript.py %load -r 5-10 myscript.py %load -r 10-20,30,40: foo.py %load -s MyClass,wonder_function myscript.py %load -n MyClass %load -n my_module.wonder_function """ opts, args = self.parse_options(arg_s, 'yns:r:') if not args: raise UsageError('Missing filename, URL, input history range, ' 'macro, or element in the user namespace.') search_ns = 'n' in opts contents = self.shell.find_user_code(args, search_ns=search_ns) if 's' in opts: try: blocks, not_found = extract_symbols(contents, opts['s']) except SyntaxError: # non python code error("Unable to parse the input as valid Python code") return if len(not_found) == 1: warn('The symbol `%s` was not found' % not_found[0]) elif len(not_found) > 1: warn('The symbols %s were not found' % get_text_list(not_found, wrap_item_with='`')) contents = '\n'.join(blocks) if 'r' in opts: ranges = opts['r'].replace(',', ' ') lines = contents.split('\n') slices = extract_code_ranges(ranges) contents = [lines[slice(*slc)] for slc in slices] contents = '\n'.join( strip_initial_indent(chain.from_iterable(contents))) l = len(contents) # 200 000 is ~ 2500 full 80 character lines # so in average, more than 5000 lines if l > 200000 and 'y' not in opts: try: ans = self.shell.ask_yes_no(("The text you're trying to load seems pretty big"\ " (%d characters). Continue (y/[N]) ?" % l), default='n' ) except StdinNotImplementedError: #assume yes if raw input not implemented ans = True if ans is False: print('Operation cancelled.') return contents = "# %load {}\n".format(arg_s) + contents self.shell.set_next_input(contents, replace=True)
def addscript(self, pars='', cell=None): """ This works both as **%addscript** and as **%%addscript** This magic command can either take a local filename, element in the namespace or history range (see %history), or the current cell content Usage: %addscript -p project n1-n2 n3-n4 ... n5 .. n6 ... or %%addscript -p project ...code lines ... Options: -p <string> Name of the project where the script will be stored. If not provided, a project with a standard name : `proj` is searched. -o <string> script name -s <symbols> Specify function or classes to load from python source. -a append to the current script instead of overwriting it. -n search symbol in the current namespace Examples -------- .. sourcecode:: ipython In[1]: %addscript myscript.py In[2]: %addscript 7-27 In[3]: %addscript -s MyClass,myfunction myscript.py In[4]: %addscript MyClass In[5]: %addscript mymodule.myfunction """ opts, args = self.parse_options(pars, 'p:o:s:n:a') # append = 'a' in opts # mode = 'a' if append else 'w' search_ns = 'n' in opts if not args and not cell and not search_ns: # pragma: no cover raise UsageError('Missing filename, input history range, ' 'or element in the user namespace.\n ' 'If no argument are given then the cell content ' 'should ' 'not be empty') name = 'script' if 'o' in opts: name = opts['o'] proj = 'proj' if 'p' in opts: proj = opts['p'] if proj not in self.shell.user_ns: # pragma: no cover raise ValueError('Cannot find any project with name `{}` in the ' 'namespace.'.format(proj)) # get the proj object projobj = self.shell.user_ns[proj] contents = "" if search_ns: contents += "\n" + self.shell.find_user_code( opts['n'], search_ns=search_ns) + "\n" args = " ".join(args) if args.strip(): contents += "\n" + self.shell.find_user_code( args, search_ns=search_ns) + "\n" if 's' in opts: # pragma: no cover try: blocks, not_found = extract_symbols(contents, opts['s']) except SyntaxError: # non python code logging.error("Unable to parse the input as valid Python code") return if len(not_found) == 1: warnings.warn('The symbol `%s` was not found' % not_found[0]) elif len(not_found) > 1: warnings.warn('The symbols %s were not found' % get_text_list(not_found, wrap_item_with='`')) contents = '\n'.join(blocks) if cell: contents += "\n" + cell # import delayed to avoid circular import error from spectrochempy.core.scripts.script import Script script = Script(name, content=contents) projobj[name] = script return "Script {} created.".format(name)
def load(self, arg_s): """Load code into the current frontend. Usage:\\ %load [options] source where source can be a filename, URL, input history range, macro, or element in the user namespace Options: -r <lines>: Specify lines or ranges of lines to load from the source. Ranges could be specified as x-y (x..y) or in python-style x:y (x..(y-1)). Both limits x and y can be left blank (meaning the beginning and end of the file, respectively). -s <symbols>: Specify function or classes to load from python source. -y : Don't ask confirmation for loading source above 200 000 characters. -n : Include the user's namespace when searching for source code. This magic command can either take a local filename, a URL, an history range (see %history) or a macro as argument, it will prompt for confirmation before loading source with more than 200 000 characters, unless -y flag is passed or if the frontend does not support raw_input:: %load myscript.py %load 7-27 %load myMacro %load http://www.example.com/myscript.py %load -r 5-10 myscript.py %load -r 10-20,30,40: foo.py %load -s MyClass,wonder_function myscript.py %load -n MyClass %load -n my_module.wonder_function """ opts, args = self.parse_options(arg_s, "yns:r:") if not args: raise UsageError("Missing filename, URL, input history range, " "macro, or element in the user namespace.") search_ns = "n" in opts contents = self.shell.find_user_code(args, search_ns=search_ns) if "s" in opts: try: blocks, not_found = extract_symbols(contents, opts["s"]) except SyntaxError: # non python code error("Unable to parse the input as valid Python code") return if len(not_found) == 1: warn("The symbol `%s` was not found" % not_found[0]) elif len(not_found) > 1: warn("The symbols %s were not found" % get_text_list(not_found, wrap_item_with="`")) contents = "\n".join(blocks) if "r" in opts: ranges = opts["r"].replace(",", " ") lines = contents.split("\n") slices = extract_code_ranges(ranges) contents = [lines[slice(*slc)] for slc in slices] contents = "\n".join(chain.from_iterable(contents)) l = len(contents) # 200 000 is ~ 2500 full 80 caracter lines # so in average, more than 5000 lines if l > 200000 and "y" not in opts: try: ans = self.shell.ask_yes_no( ("The text you're trying to load seems pretty big" " (%d characters). Continue (y/[N]) ?" % l), default="n", ) except StdinNotImplementedError: # asume yes if raw input not implemented ans = True if ans is False: print("Operation cancelled.") return contents = "# %load {}\n".format(arg_s) + contents self.shell.set_next_input(contents, replace=True)
def addscript(self, pars="", cell=None): """ This works both as **%addscript** and as **%%addscript**. This magic command can either take a local filename, element in the namespace or history range (see %history), or the current cell content. Usage: %addscript -p project n1-n2 n3-n4 ... n5 .. n6 ... or %%addscript -p project ...code lines ... Options: -p <string> Name of the project where the script will be stored. If not provided, a project with a standard name : `proj` is searched. -o <string> script name. -s <symbols> Specify function or classes to load from python source. -a append to the current script instead of overwriting it. -n Search symbol in the current namespace. Examples -------- .. sourcecode:: ipython In[1]: %addscript myscript.py In[2]: %addscript 7-27 In[3]: %addscript -s MyClass,myfunction myscript.py In[4]: %addscript MyClass In[5]: %addscript mymodule.myfunction """ opts, args = self.parse_options(pars, "p:o:s:n:a") # append = 'a' in opts # mode = 'a' if append else 'w' search_ns = "n" in opts if not args and not cell and not search_ns: # pragma: no cover raise UsageError("Missing filename, input history range, " "or element in the user namespace.\n " "If no argument are given then the cell content " "should " "not be empty") name = "script" if "o" in opts: name = opts["o"] proj = "proj" if "p" in opts: proj = opts["p"] if proj not in self.shell.user_ns: # pragma: no cover raise ValueError( f"Cannot find any project with name `{proj}` in the namespace." ) # get the proj object projobj = self.shell.user_ns[proj] contents = "" if search_ns: contents += ("\n" + self.shell.find_user_code( opts["n"], search_ns=search_ns) + "\n") args = " ".join(args) if args.strip(): contents += ("\n" + self.shell.find_user_code(args, search_ns=search_ns) + "\n") if "s" in opts: # pragma: no cover try: blocks, not_found = extract_symbols(contents, opts["s"]) except SyntaxError: # non python code logging.error("Unable to parse the input as valid Python code") return None if len(not_found) == 1: warnings.warn(f"The symbol `{not_found[0]}` was not found") elif len(not_found) > 1: sym = get_text_list(not_found, wrap_item_with="`") warnings.warn(f"The symbols {sym} were not found") contents = "\n".join(blocks) if cell: contents += "\n" + cell # import delayed to avoid circular import error from spectrochempy.core.scripts.script import Script script = Script(name, content=contents) projobj[name] = script return f"Script {name} created."