diff --git a/IPython/Extensions/ipy_which.py b/IPython/Extensions/ipy_which.py new file mode 100644 index 0000000..73de12c --- /dev/null +++ b/IPython/Extensions/ipy_which.py @@ -0,0 +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) + diff --git a/IPython/UserConfig/ipy_profile_sh.py b/IPython/UserConfig/ipy_profile_sh.py index 876709a..3722b2a 100644 --- a/IPython/UserConfig/ipy_profile_sh.py +++ b/IPython/UserConfig/ipy_profile_sh.py @@ -31,6 +31,7 @@ def main(): # beefed up %env is handy in shell mode import envpersist + import ipy_which ip.ex('import os') diff --git a/IPython/ipapi.py b/IPython/ipapi.py index 7595c68..5f54e82 100644 --- a/IPython/ipapi.py +++ b/IPython/ipapi.py @@ -300,6 +300,7 @@ class IPApi: pre,fn,rest = self.IP.split_user_input(line) res = pre + self.IP.expand_aliases(fn,rest) + return res def defalias(self, name, cmd): """ Define a new alias diff --git a/doc/ChangeLog b/doc/ChangeLog index ad463a9..f328793 100644 --- a/doc/ChangeLog +++ b/doc/ChangeLog @@ -1,3 +1,12 @@ +2007-04-25 Ville Vainio + + * Extensions/ipy_which.py: added extension for %which magic, works + a lot like unix 'which' but also finds and expands aliases, and + allows wildcards. + + * ipapi.py (expand_alias): Now actually *return* the expanded alias, + as opposed to returning nothing. + 2007-04-22 J�rgen Stenarson * Fix bug in iplib.py/safe_execfile when launching ipython with a script like ipython.py foo.py