diff --git a/IPython/Extensions/ipy_exportdb.py b/IPython/Extensions/ipy_exportdb.py index 5da15c4..54b5f2f 100644 --- a/IPython/Extensions/ipy_exportdb.py +++ b/IPython/Extensions/ipy_exportdb.py @@ -1,73 +1,73 @@ -import IPython.ipapi -ip = IPython.ipapi.get() - -import os,pprint - -def export(filename = None): - - lines = ['import IPython.ipapi', 'ip = IPython.ipapi.get()',''] - - vars = ip.db.keys('autorestore/*') - vars.sort() - varstomove = [] - get = ip.db.get - - macros = [] - variables = [] - - for var in vars: - k = os.path.basename(var) - v = get(var) - - if k.startswith('_'): - continue - if isinstance(v, IPython.macro.Macro): - macros.append((k,v)) - if type(v) in [int, str, float]: - variables.append((k,v)) - - - - if macros: - lines.extend(['# === Macros ===' ,'']) - for k,v in macros: - lines.append("ip.defmacro('%s'," % k) - for line in v.value.splitlines(): - lines.append(' ' + repr(line+'\n')) - lines.extend([')', '']) - - if variables: - lines.extend(['','# === Variables ===','']) - for k,v in variables: - varstomove.append(k) - lines.append('%s = %s' % (k,repr(v))) - - lines.append('ip.to_user_ns("%s")' % (' '.join(varstomove))) - - bkms = ip.db.get('bookmarks',{}) - - if bkms: - lines.extend(['','# === Bookmarks ===','']) - lines.append("ip.db['bookmarks'] = %s " % pprint.pformat(bkms, indent = 2) ) - - aliases = ip.db.get('stored_aliases', {} ) - - if aliases: - lines.extend(['','# === Alias definitions ===','']) - for k,v in aliases.items(): - lines.append("ip.defalias('%s', %s)" % (k, repr(v[1]))) - - env = ip.db.get('stored_env') - if env: - lines.extend(['','# === Stored env vars ===','']) - lines.append("ip.db['stored_env'] = %s " % pprint.pformat(env, indent = 2) ) - - - - out = '\n'.join(lines) - - if filename: - open(filename,'w').write(out) - else: - print out - +import IPython.ipapi +ip = IPython.ipapi.get() + +import os,pprint + +def export(filename = None): + + lines = ['import IPython.ipapi', 'ip = IPython.ipapi.get()',''] + + vars = ip.db.keys('autorestore/*') + vars.sort() + varstomove = [] + get = ip.db.get + + macros = [] + variables = [] + + for var in vars: + k = os.path.basename(var) + v = get(var) + + if k.startswith('_'): + continue + if isinstance(v, IPython.macro.Macro): + macros.append((k,v)) + if type(v) in [int, str, float]: + variables.append((k,v)) + + + + if macros: + lines.extend(['# === Macros ===' ,'']) + for k,v in macros: + lines.append("ip.defmacro('%s'," % k) + for line in v.value.splitlines(): + lines.append(' ' + repr(line+'\n')) + lines.extend([')', '']) + + if variables: + lines.extend(['','# === Variables ===','']) + for k,v in variables: + varstomove.append(k) + lines.append('%s = %s' % (k,repr(v))) + + lines.append('ip.to_user_ns("%s")' % (' '.join(varstomove))) + + bkms = ip.db.get('bookmarks',{}) + + if bkms: + lines.extend(['','# === Bookmarks ===','']) + lines.append("ip.db['bookmarks'] = %s " % pprint.pformat(bkms, indent = 2) ) + + aliases = ip.db.get('stored_aliases', {} ) + + if aliases: + lines.extend(['','# === Alias definitions ===','']) + for k,v in aliases.items(): + lines.append("ip.defalias('%s', %s)" % (k, repr(v[1]))) + + env = ip.db.get('stored_env') + if env: + lines.extend(['','# === Stored env vars ===','']) + lines.append("ip.db['stored_env'] = %s " % pprint.pformat(env, indent = 2) ) + + + + out = '\n'.join(lines) + + if filename: + open(filename,'w').write(out) + else: + print out + diff --git a/IPython/Extensions/ipy_extutil.py b/IPython/Extensions/ipy_extutil.py index 4a01615..c35cbc3 100644 --- a/IPython/Extensions/ipy_extutil.py +++ b/IPython/Extensions/ipy_extutil.py @@ -1,43 +1,43 @@ -""" IPython extension management tools. - -After installation, you'll have the 'extutil' object in your namespace. -to. -""" - -# for the purposes of this module, every module that has the name 'ip' globally -# installed as below is an IPython extension - -import IPython.ipapi -ip = IPython.ipapi.get() - -import sys,textwrap,inspect - -def indent(s, ind= ' '): - return '\n'.join([ind +l for l in s.splitlines()]) - -class ExtUtil: - """ IPython extensios (ipy_* etc.) management utilities """ - - def describe(self): - for n,mod in self._active(): - doc = inspect.getdoc(mod) - if doc: - print '== %s ==' % n - print indent(doc) - - - def ls(self): - """ Show list of installed extensions. """ - for n,m in self._active(): - print '%-20s %s' % (n,m.__file__.replace('\\','/')) - def _active(self): - act = [] - for mname,m in sys.modules.items(): - o = getattr(m, 'ip', None) - if isinstance(o, IPython.ipapi.IPApi): - act.append((mname,m)) - act.sort() - return act - -extutil = ExtUtil() -ip.to_user_ns('extutil') +""" IPython extension management tools. + +After installation, you'll have the 'extutil' object in your namespace. +to. +""" + +# for the purposes of this module, every module that has the name 'ip' globally +# installed as below is an IPython extension + +import IPython.ipapi +ip = IPython.ipapi.get() + +import sys,textwrap,inspect + +def indent(s, ind= ' '): + return '\n'.join([ind +l for l in s.splitlines()]) + +class ExtUtil: + """ IPython extensios (ipy_* etc.) management utilities """ + + def describe(self): + for n,mod in self._active(): + doc = inspect.getdoc(mod) + if doc: + print '== %s ==' % n + print indent(doc) + + + def ls(self): + """ Show list of installed extensions. """ + for n,m in self._active(): + print '%-20s %s' % (n,m.__file__.replace('\\','/')) + def _active(self): + act = [] + for mname,m in sys.modules.items(): + o = getattr(m, 'ip', None) + if isinstance(o, IPython.ipapi.IPApi): + act.append((mname,m)) + act.sort() + return act + +extutil = ExtUtil() +ip.to_user_ns('extutil') diff --git a/IPython/Extensions/ipy_gnuglobal.py b/IPython/Extensions/ipy_gnuglobal.py index 48bd7c1..d03babc 100644 --- a/IPython/Extensions/ipy_gnuglobal.py +++ b/IPython/Extensions/ipy_gnuglobal.py @@ -1,38 +1,38 @@ -#!/usr/bin/env python - - -""" -Add %global magic for GNU Global usage. - -http://www.gnu.org/software/global/ - -""" - -import IPython.ipapi -ip = IPython.ipapi.get() -import os - -# alter to your liking -global_bin = 'd:/opt/global/bin/global' - -def global_f(self,cmdline): - simple = 0 - if '-' not in cmdline: - cmdline = '-rx ' + cmdline - simple = 1 - - lines = [l.rstrip() for l in os.popen( global_bin + ' ' + cmdline ).readlines()] - - if simple: - parts = [l.split(None,3) for l in lines] - lines = ['%s [%s]\n%s' % (p[2].rjust(70),p[1],p[3].rstrip()) for p in parts] - print "\n".join(lines) - -ip.expose_magic('global', global_f) - -def global_completer(self,event): - compl = [l.rstrip() for l in os.popen(global_bin + ' -c ' + event.symbol).readlines()] - return compl - -ip.set_hook('complete_command', global_completer, str_key = '%global') - +#!/usr/bin/env python + + +""" +Add %global magic for GNU Global usage. + +http://www.gnu.org/software/global/ + +""" + +import IPython.ipapi +ip = IPython.ipapi.get() +import os + +# alter to your liking +global_bin = 'd:/opt/global/bin/global' + +def global_f(self,cmdline): + simple = 0 + if '-' not in cmdline: + cmdline = '-rx ' + cmdline + simple = 1 + + lines = [l.rstrip() for l in os.popen( global_bin + ' ' + cmdline ).readlines()] + + if simple: + parts = [l.split(None,3) for l in lines] + lines = ['%s [%s]\n%s' % (p[2].rjust(70),p[1],p[3].rstrip()) for p in parts] + print "\n".join(lines) + +ip.expose_magic('global', global_f) + +def global_completer(self,event): + compl = [l.rstrip() for l in os.popen(global_bin + ' -c ' + event.symbol).readlines()] + return compl + +ip.set_hook('complete_command', global_completer, str_key = '%global') + diff --git a/IPython/Extensions/ipy_legacy.py b/IPython/Extensions/ipy_legacy.py index cd16fef..3a50aae 100644 --- a/IPython/Extensions/ipy_legacy.py +++ b/IPython/Extensions/ipy_legacy.py @@ -1,251 +1,252 @@ -""" Legacy stuff - -Various stuff that are there for historical / familiarity reasons. - -This is automatically imported by default profile, though not other profiles -(e.g. 'sh' profile). - -Stuff that is considered obsolete / redundant is gradually moved here. - -""" - -import IPython.ipapi -ip = IPython.ipapi.get() - -import os,sys - -from IPython.genutils import * - -# use ? -def magic_pdef(self, parameter_s='', namespaces=None): - """Print the definition header for any callable object. - - If the object is a class, print the constructor information.""" - self._inspect('pdef',parameter_s, namespaces) - -ip.expose_magic("pdef", magic_pdef) - -# use ? -def magic_pdoc(self, parameter_s='', namespaces=None): - """Print the docstring for an object. - - If the given object is a class, it will print both the class and the - constructor docstrings.""" - self._inspect('pdoc',parameter_s, namespaces) - -ip.expose_magic("pdoc", magic_pdoc) - -# use ?? -def magic_psource(self, parameter_s='', namespaces=None): - """Print (or run through pager) the source code for an object.""" - self._inspect('psource',parameter_s, namespaces) - -ip.expose_magic("pdoc", magic_psource) - -# use ? -def magic_pfile(self, parameter_s=''): - """Print (or run through pager) the file where an object is defined. - - The file opens at the line where the object definition begins. IPython - will honor the environment variable PAGER if set, and otherwise will - do its best to print the file in a convenient form. - - If the given argument is not an object currently defined, IPython will - try to interpret it as a filename (automatically adding a .py extension - if needed). You can thus use %pfile as a syntax highlighting code - viewer.""" - - # first interpret argument as an object name - out = self._inspect('pfile',parameter_s) - # if not, try the input as a filename - if out == 'not found': - try: - filename = get_py_filename(parameter_s) - except IOError,msg: - print msg - return - page(self.shell.inspector.format(file(filename).read())) - -ip.expose_magic("pfile", magic_pfile) - -# use rehashx - -def magic_rehash(self, parameter_s = ''): - """Update the alias table with all entries in $PATH. - - This version does no checks on execute permissions or whether the - contents of $PATH are truly files (instead of directories or something - else). For such a safer (but slower) version, use %rehashx.""" - - # This function (and rehashx) manipulate the alias_table directly - # rather than calling magic_alias, for speed reasons. A rehash on a - # typical Linux box involves several thousand entries, so efficiency - # here is a top concern. - - path = filter(os.path.isdir,os.environ.get('PATH','').split(os.pathsep)) - alias_table = self.shell.alias_table - for pdir in path: - for ff in os.listdir(pdir): - # each entry in the alias table must be (N,name), where - # N is the number of positional arguments of the alias. - alias_table[ff] = (0,ff) - # Make sure the alias table doesn't contain keywords or builtins - self.shell.alias_table_validate() - # Call again init_auto_alias() so we get 'rm -i' and other modified - # aliases since %rehash will probably clobber them - self.shell.init_auto_alias() - -ip.expose_magic("rehash", magic_rehash) - -#use cd - -def magic_dhist(self, parameter_s=''): - """Print your history of visited directories. - - %dhist -> print full history\\ - %dhist n -> print last n entries only\\ - %dhist n1 n2 -> print entries between n1 and n2 (n1 not included)\\ - - This history is automatically maintained by the %cd command, and - always available as the global list variable _dh. You can use %cd - - to go to directory number .""" - - dh = self.shell.user_ns['_dh'] - if parameter_s: - try: - args = map(int,parameter_s.split()) - except: - self.arg_err(Magic.magic_dhist) - return - if len(args) == 1: - ini,fin = max(len(dh)-(args[0]),0),len(dh) - elif len(args) == 2: - ini,fin = args - else: - self.arg_err(Magic.magic_dhist) - return - else: - ini,fin = 0,len(dh) - nlprint(dh, - header = 'Directory history (kept in _dh)', - start=ini,stop=fin) - -ip.expose_magic("dhist", magic_dhist) - -# Exit -def magic_Quit(self, parameter_s=''): - """Exit IPython without confirmation (like %Exit).""" - - self.shell.exit_now = True - -ip.expose_magic("Quit", magic_Quit) - - -# make it autocallable fn if you really need it -def magic_p(self, parameter_s=''): - """Just a short alias for Python's 'print'.""" - exec 'print ' + parameter_s in self.shell.user_ns - -ip.expose_magic("p", magic_p) - -# up + enter. One char magic. -def magic_r(self, parameter_s=''): - """Repeat previous input. - - If given an argument, repeats the previous command which starts with - the same string, otherwise it just repeats the previous input. - - Shell escaped commands (with ! as first character) are not recognized - by this system, only pure python code and magic commands. - """ - - start = parameter_s.strip() - esc_magic = self.shell.ESC_MAGIC - # Identify magic commands even if automagic is on (which means - # the in-memory version is different from that typed by the user). - if self.shell.rc.automagic: - start_magic = esc_magic+start - else: - start_magic = start - # Look through the input history in reverse - for n in range(len(self.shell.input_hist)-2,0,-1): - input = self.shell.input_hist[n] - # skip plain 'r' lines so we don't recurse to infinity - if input != '_ip.magic("r")\n' and \ - (input.startswith(start) or input.startswith(start_magic)): - #print 'match',`input` # dbg - print 'Executing:',input, - self.shell.runlines(input) - return - print 'No previous input matching `%s` found.' % start - -ip.expose_magic("r", magic_r) - - -# use _ip.option.automagic - -def magic_automagic(self, parameter_s = ''): - """Make magic functions callable without having to type the initial %. - - Without argumentsl toggles on/off (when off, you must call it as - %automagic, of course). With arguments it sets the value, and you can - use any of (case insensitive): - - - on,1,True: to activate - - - off,0,False: to deactivate. - - Note that magic functions have lowest priority, so if there's a - variable whose name collides with that of a magic fn, automagic won't - work for that function (you get the variable instead). However, if you - delete the variable (del var), the previously shadowed magic function - becomes visible to automagic again.""" - - rc = self.shell.rc - arg = parameter_s.lower() - if parameter_s in ('on','1','true'): - rc.automagic = True - elif parameter_s in ('off','0','false'): - rc.automagic = False - else: - rc.automagic = not rc.automagic - print '\n' + Magic.auto_status[rc.automagic] - -ip.expose_magic("automagic", magic_automagic) - -# use _ip.options.autocall -def magic_autocall(self, parameter_s = ''): - """Make functions callable without having to type parentheses. - - Usage: - - %autocall [mode] - - The mode can be one of: 0->Off, 1->Smart, 2->Full. If not given, the - value is toggled on and off (remembering the previous state).""" - - rc = self.shell.rc - - if parameter_s: - arg = int(parameter_s) - else: - arg = 'toggle' - - if not arg in (0,1,2,'toggle'): - error('Valid modes: (0->Off, 1->Smart, 2->Full') - return - - if arg in (0,1,2): - rc.autocall = arg - else: # toggle - if rc.autocall: - self._magic_state.autocall_save = rc.autocall - rc.autocall = 0 - else: - try: - rc.autocall = self._magic_state.autocall_save - except AttributeError: - rc.autocall = self._magic_state.autocall_save = 1 - - print "Automatic calling is:",['OFF','Smart','Full'][rc.autocall] - -ip.expose_magic("autocall", magic_autocall) \ No newline at end of file +""" Legacy stuff + +Various stuff that are there for historical / familiarity reasons. + +This is automatically imported by default profile, though not other profiles +(e.g. 'sh' profile). + +Stuff that is considered obsolete / redundant is gradually moved here. + +""" + +import IPython.ipapi +ip = IPython.ipapi.get() + +import os,sys + +from IPython.genutils import * + +# use ? +def magic_pdef(self, parameter_s='', namespaces=None): + """Print the definition header for any callable object. + + If the object is a class, print the constructor information.""" + self._inspect('pdef',parameter_s, namespaces) + +ip.expose_magic("pdef", magic_pdef) + +# use ? +def magic_pdoc(self, parameter_s='', namespaces=None): + """Print the docstring for an object. + + If the given object is a class, it will print both the class and the + constructor docstrings.""" + self._inspect('pdoc',parameter_s, namespaces) + +ip.expose_magic("pdoc", magic_pdoc) + +# use ?? +def magic_psource(self, parameter_s='', namespaces=None): + """Print (or run through pager) the source code for an object.""" + self._inspect('psource',parameter_s, namespaces) + +ip.expose_magic("pdoc", magic_psource) + +# use ? +def magic_pfile(self, parameter_s=''): + """Print (or run through pager) the file where an object is defined. + + The file opens at the line where the object definition begins. IPython + will honor the environment variable PAGER if set, and otherwise will + do its best to print the file in a convenient form. + + If the given argument is not an object currently defined, IPython will + try to interpret it as a filename (automatically adding a .py extension + if needed). You can thus use %pfile as a syntax highlighting code + viewer.""" + + # first interpret argument as an object name + out = self._inspect('pfile',parameter_s) + # if not, try the input as a filename + if out == 'not found': + try: + filename = get_py_filename(parameter_s) + except IOError,msg: + print msg + return + page(self.shell.inspector.format(file(filename).read())) + +ip.expose_magic("pfile", magic_pfile) + +# use rehashx + +def magic_rehash(self, parameter_s = ''): + """Update the alias table with all entries in $PATH. + + This version does no checks on execute permissions or whether the + contents of $PATH are truly files (instead of directories or something + else). For such a safer (but slower) version, use %rehashx.""" + + # This function (and rehashx) manipulate the alias_table directly + # rather than calling magic_alias, for speed reasons. A rehash on a + # typical Linux box involves several thousand entries, so efficiency + # here is a top concern. + + path = filter(os.path.isdir,os.environ.get('PATH','').split(os.pathsep)) + alias_table = self.shell.alias_table + for pdir in path: + for ff in os.listdir(pdir): + # each entry in the alias table must be (N,name), where + # N is the number of positional arguments of the alias. + alias_table[ff] = (0,ff) + # Make sure the alias table doesn't contain keywords or builtins + self.shell.alias_table_validate() + # Call again init_auto_alias() so we get 'rm -i' and other modified + # aliases since %rehash will probably clobber them + self.shell.init_auto_alias() + +ip.expose_magic("rehash", magic_rehash) + +#use cd - +def magic_dhist(self, parameter_s=''): + """Print your history of visited directories. + + %dhist -> print full history\\ + %dhist n -> print last n entries only\\ + %dhist n1 n2 -> print entries between n1 and n2 (n1 not included)\\ + + This history is automatically maintained by the %cd command, and + always available as the global list variable _dh. You can use %cd - + to go to directory number .""" + + dh = self.shell.user_ns['_dh'] + if parameter_s: + try: + args = map(int,parameter_s.split()) + except: + self.arg_err(Magic.magic_dhist) + return + if len(args) == 1: + ini,fin = max(len(dh)-(args[0]),0),len(dh) + elif len(args) == 2: + ini,fin = args + else: + self.arg_err(Magic.magic_dhist) + return + else: + ini,fin = 0,len(dh) + nlprint(dh, + header = 'Directory history (kept in _dh)', + start=ini,stop=fin) + +ip.expose_magic("dhist", magic_dhist) + +# Exit +def magic_Quit(self, parameter_s=''): + """Exit IPython without confirmation (like %Exit).""" + + self.shell.exit_now = True + +ip.expose_magic("Quit", magic_Quit) + + +# make it autocallable fn if you really need it +def magic_p(self, parameter_s=''): + """Just a short alias for Python's 'print'.""" + exec 'print ' + parameter_s in self.shell.user_ns + +ip.expose_magic("p", magic_p) + +# up + enter. One char magic. +def magic_r(self, parameter_s=''): + """Repeat previous input. + + If given an argument, repeats the previous command which starts with + the same string, otherwise it just repeats the previous input. + + Shell escaped commands (with ! as first character) are not recognized + by this system, only pure python code and magic commands. + """ + + start = parameter_s.strip() + esc_magic = self.shell.ESC_MAGIC + # Identify magic commands even if automagic is on (which means + # the in-memory version is different from that typed by the user). + if self.shell.rc.automagic: + start_magic = esc_magic+start + else: + start_magic = start + # Look through the input history in reverse + for n in range(len(self.shell.input_hist)-2,0,-1): + input = self.shell.input_hist[n] + # skip plain 'r' lines so we don't recurse to infinity + if input != '_ip.magic("r")\n' and \ + (input.startswith(start) or input.startswith(start_magic)): + #print 'match',`input` # dbg + print 'Executing:',input, + self.shell.runlines(input) + return + print 'No previous input matching `%s` found.' % start + +ip.expose_magic("r", magic_r) + + +# use _ip.option.automagic + +def magic_automagic(self, parameter_s = ''): + """Make magic functions callable without having to type the initial %. + + Without argumentsl toggles on/off (when off, you must call it as + %automagic, of course). With arguments it sets the value, and you can + use any of (case insensitive): + + - on,1,True: to activate + + - off,0,False: to deactivate. + + Note that magic functions have lowest priority, so if there's a + variable whose name collides with that of a magic fn, automagic won't + work for that function (you get the variable instead). However, if you + delete the variable (del var), the previously shadowed magic function + becomes visible to automagic again.""" + + rc = self.shell.rc + arg = parameter_s.lower() + if parameter_s in ('on','1','true'): + rc.automagic = True + elif parameter_s in ('off','0','false'): + rc.automagic = False + else: + rc.automagic = not rc.automagic + print '\n' + Magic.auto_status[rc.automagic] + +ip.expose_magic("automagic", magic_automagic) + +# use _ip.options.autocall +def magic_autocall(self, parameter_s = ''): + """Make functions callable without having to type parentheses. + + Usage: + + %autocall [mode] + + The mode can be one of: 0->Off, 1->Smart, 2->Full. If not given, the + value is toggled on and off (remembering the previous state).""" + + rc = self.shell.rc + + if parameter_s: + arg = int(parameter_s) + else: + arg = 'toggle' + + if not arg in (0,1,2,'toggle'): + error('Valid modes: (0->Off, 1->Smart, 2->Full') + return + + if arg in (0,1,2): + rc.autocall = arg + else: # toggle + if rc.autocall: + self._magic_state.autocall_save = rc.autocall + rc.autocall = 0 + else: + try: + rc.autocall = self._magic_state.autocall_save + except AttributeError: + rc.autocall = self._magic_state.autocall_save = 1 + + print "Automatic calling is:",['OFF','Smart','Full'][rc.autocall] + +ip.expose_magic("autocall", magic_autocall) + diff --git a/IPython/Extensions/ipy_profile_none.py b/IPython/Extensions/ipy_profile_none.py index 045354b..195aa87 100644 --- a/IPython/Extensions/ipy_profile_none.py +++ b/IPython/Extensions/ipy_profile_none.py @@ -1,4 +1,4 @@ -""" Config file for 'default' profile """ - -# get various stuff that are there for historical / familiarity reasons +""" Config file for 'default' profile """ + +# get various stuff that are there for historical / familiarity reasons import ipy_legacy \ No newline at end of file diff --git a/IPython/Extensions/ipy_profile_scipy.py b/IPython/Extensions/ipy_profile_scipy.py index 064f191..08155e4 100644 --- a/IPython/Extensions/ipy_profile_scipy.py +++ b/IPython/Extensions/ipy_profile_scipy.py @@ -1,25 +1,25 @@ -""" IPython 'sci' profile - -Replaces the old scipy profile. - -""" - - -import IPython.ipapi -import ipy_defaults - -def main(): - ip = IPython.ipapi.get() - - try: - ip.ex("import scipy") - ip.ex("import numpy") - - ip.ex("from scipy import *") - ip.ex("from numpy import *") - print "SciPy profile successfully loaded." - except ImportError: - print "Unable to start scipy profile, are scipy and numpy installed?" - - +""" IPython 'sci' profile + +Replaces the old scipy profile. + +""" + + +import IPython.ipapi +import ipy_defaults + +def main(): + ip = IPython.ipapi.get() + + try: + ip.ex("import scipy") + ip.ex("import numpy") + + ip.ex("from scipy import *") + ip.ex("from numpy import *") + print "SciPy profile successfully loaded." + except ImportError: + print "Unable to start scipy profile, are scipy and numpy installed?" + + main() \ No newline at end of file diff --git a/IPython/Extensions/ipy_render.py b/IPython/Extensions/ipy_render.py index 44b1060..3946a87 100644 --- a/IPython/Extensions/ipy_render.py +++ b/IPython/Extensions/ipy_render.py @@ -1,68 +1,68 @@ -#!/usr/bin/env python - -""" IPython extension: Render templates from variables and paste to clipbard """ - -import IPython.ipapi - -ip = IPython.ipapi.get() - -from string import Template -import sys,os - -from IPython.Itpl import itplns - -def toclip_w32(s): - """ Places contents of s to clipboard - - Needs pyvin32 to work: - http://sourceforge.net/projects/pywin32/ - """ - import win32clipboard as cl - import win32con - cl.OpenClipboard() - cl.EmptyClipboard() - cl.SetClipboardText( s.replace('\n','\r\n' )) - cl.CloseClipboard() - -try: - import win32clipboard - toclip = toclip_w32 -except ImportError: - def toclip(s): pass - - -def render(tmpl): - """ Render a template (Itpl format) from ipython variables - - Example: - - $ import ipy_render - $ my_name = 'Bob' # %store this for convenience - $ t_submission_form = "Submission report, author: $my_name" # %store also - $ render t_submission_form - - => returns "Submission report, author: Bob" and copies to clipboard on win32 - - # if template exist as a file, read it. Note: ;f hei vaan => f("hei vaan") - $ ;render c:/templates/greeting.txt - - Template examples (Ka-Ping Yee's Itpl library): - - Here is a $string. - Here is a $module.member. - Here is an $object.member. - Here is a $functioncall(with, arguments). - Here is an ${arbitrary + expression}. - Here is an $array[3] member. - Here is a $dictionary['member']. - """ - - if os.path.isfile(tmpl): - tmpl = open(tmpl).read() - - res = itplns(tmpl, ip.user_ns) - toclip(res) - return res - -ip.to_user_ns('render') +#!/usr/bin/env python + +""" IPython extension: Render templates from variables and paste to clipbard """ + +import IPython.ipapi + +ip = IPython.ipapi.get() + +from string import Template +import sys,os + +from IPython.Itpl import itplns + +def toclip_w32(s): + """ Places contents of s to clipboard + + Needs pyvin32 to work: + http://sourceforge.net/projects/pywin32/ + """ + import win32clipboard as cl + import win32con + cl.OpenClipboard() + cl.EmptyClipboard() + cl.SetClipboardText( s.replace('\n','\r\n' )) + cl.CloseClipboard() + +try: + import win32clipboard + toclip = toclip_w32 +except ImportError: + def toclip(s): pass + + +def render(tmpl): + """ Render a template (Itpl format) from ipython variables + + Example: + + $ import ipy_render + $ my_name = 'Bob' # %store this for convenience + $ t_submission_form = "Submission report, author: $my_name" # %store also + $ render t_submission_form + + => returns "Submission report, author: Bob" and copies to clipboard on win32 + + # if template exist as a file, read it. Note: ;f hei vaan => f("hei vaan") + $ ;render c:/templates/greeting.txt + + Template examples (Ka-Ping Yee's Itpl library): + + Here is a $string. + Here is a $module.member. + Here is an $object.member. + Here is a $functioncall(with, arguments). + Here is an ${arbitrary + expression}. + Here is an $array[3] member. + Here is a $dictionary['member']. + """ + + if os.path.isfile(tmpl): + tmpl = open(tmpl).read() + + res = itplns(tmpl, ip.user_ns) + toclip(res) + return res + +ip.to_user_ns('render') \ No newline at end of file diff --git a/IPython/Extensions/ipy_which.py b/IPython/Extensions/ipy_which.py index 73de12c..caddd56 100644 --- a/IPython/Extensions/ipy_which.py +++ b/IPython/Extensions/ipy_which.py @@ -1,70 +1,70 @@ -r""" %which magic command - -%which => search PATH for files matching PATH. Also scans aliases - -""" - -import IPython.ipapi -ip = IPython.ipapi.get() - -import os,sys -from fnmatch import fnmatch -def which(fname): - fullpath = filter(os.path.isdir,os.environ['PATH'].split(os.pathsep)) - - if '.' not in fullpath: - fullpath = ['.'] + fullpath - fn = fname - for p in fullpath: - for f in os.listdir(p): - head, ext = os.path.splitext(f) - if f == fn or fnmatch(head, fn): - yield os.path.join(p,f) - return - -def which_alias(fname): - for al, tgt in ip.IP.alias_table.items(): - if not (al == fname or fnmatch(al, fname)): - continue - trg = tgt[1] - - trans = ip.expand_alias(trg) - cmd = trans.split(None,1)[0] - print al,"->",trans - for realcmd in which(cmd): - print " ==",realcmd - -def which_f(self, arg): - r""" %which => search PATH for files matching cmd. Also scans aliases. - - Traverses PATH and prints all files (not just executables!) that match the - pattern on command line. Probably more useful in finding stuff - interactively than 'which', which only prints the first matching item. - - Also discovers and expands aliases, so you'll see what will be executed - when you call an alias. - - Example: - - [~]|62> %which d - d -> ls -F --color=auto - == c:\cygwin\bin\ls.exe - c:\cygwin\bin\d.exe - - [~]|64> %which diff* - diff3 -> diff3 - == c:\cygwin\bin\diff3.exe - diff -> diff - == c:\cygwin\bin\diff.exe - c:\cygwin\bin\diff.exe - c:\cygwin\bin\diff3.exe - - """ - - which_alias(arg) - - for e in which(arg): - print e - -ip.expose_magic("which",which_f) - +r""" %which magic command + +%which => search PATH for files matching PATH. Also scans aliases + +""" + +import IPython.ipapi +ip = IPython.ipapi.get() + +import os,sys +from fnmatch import fnmatch +def which(fname): + fullpath = filter(os.path.isdir,os.environ['PATH'].split(os.pathsep)) + + if '.' not in fullpath: + fullpath = ['.'] + fullpath + fn = fname + for p in fullpath: + for f in os.listdir(p): + head, ext = os.path.splitext(f) + if f == fn or fnmatch(head, fn): + yield os.path.join(p,f) + return + +def which_alias(fname): + for al, tgt in ip.IP.alias_table.items(): + if not (al == fname or fnmatch(al, fname)): + continue + trg = tgt[1] + + trans = ip.expand_alias(trg) + cmd = trans.split(None,1)[0] + print al,"->",trans + for realcmd in which(cmd): + print " ==",realcmd + +def which_f(self, arg): + r""" %which => search PATH for files matching cmd. Also scans aliases. + + Traverses PATH and prints all files (not just executables!) that match the + pattern on command line. Probably more useful in finding stuff + interactively than 'which', which only prints the first matching item. + + Also discovers and expands aliases, so you'll see what will be executed + when you call an alias. + + Example: + + [~]|62> %which d + d -> ls -F --color=auto + == c:\cygwin\bin\ls.exe + c:\cygwin\bin\d.exe + + [~]|64> %which diff* + diff3 -> diff3 + == c:\cygwin\bin\diff3.exe + diff -> diff + == c:\cygwin\bin\diff.exe + c:\cygwin\bin\diff.exe + c:\cygwin\bin\diff3.exe + + """ + + which_alias(arg) + + for e in which(arg): + print e + +ip.expose_magic("which",which_f) +