Advertisement
DevPlayer

inpath

Oct 31st, 2011
294
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 8.52 KB | None | 0 0
  1.  
  2.  
  3. # DevPlayer@gmail.com
  4. # 2011-Oct-06
  5. # License: LGPL
  6. # Python 2.7
  7. # inpath.py
  8. # revision 0.9.0-beta
  9.  
  10. # TO DO:
  11. #   test with no PATHEXT and or no PATH environment variables
  12. #   fix for on Mac and linux/unix
  13.  
  14. import os
  15. import sys
  16. import glob
  17.  
  18. '''Find a runnable program in PATH or supplied list of paths.
  19.  
  20. Search the PATH environment variable for all runnable
  21. file names that match. Wildcards are not supported.
  22.  
  23. If at the DOS prompt you type "somecommand" and it runs
  24. you may not know where in the PATH that program is and or
  25. what file name extension the "somecommand" has.
  26.  
  27. This tool will find it.'''
  28.  
  29.  
  30. help = ['-h', '--h', '-help', '--help', '/h', '/help']
  31.  
  32.  
  33. # -----------------------------
  34. # prep the running environment
  35. if True: # <- my-trick-to-force-editor-block-folding
  36.  
  37.     # - - - - - - - - - - - -
  38.     # Microsoft usually has an environment variable PATHEXT
  39.  
  40.     if os.environ.has_key('PATHEXT'):
  41.  
  42.         # remove dups from runnables extension list;
  43.         _runnables = [ext for ext in os.environ['PATHEXT'].split(os.pathsep)]
  44.         runnables = []
  45.  
  46.         # Remember that NOT all extensions are
  47.         # ".xxx" chars long. And some filenames are like
  48.         # myfile.someext.someother_ext.ext
  49.  
  50.         for ext in _runnables:
  51.             if ext not in runnables:
  52.                 runnables.append(ext)
  53.         del _runnables, ext
  54.  
  55.     else: # No PATHEXT found
  56.  
  57.         if sys.platform == 'win32':
  58.             runnables = ['.COM', '.EXE', '.BAT']
  59.         else:
  60.             # Unix/Linux does not have that requirement
  61.             runnables = []
  62.  
  63.  
  64.     # - - - - - - - - - - - -
  65.     # The wild card is different on different OSes
  66.     # This script presumes MS and linux wildcards
  67.     # I don't know Mac wildcards
  68.  
  69.     if sys.platform == 'win32':
  70.         os_wild = '.*'
  71.     else:
  72.         os_wild = '*'
  73.  
  74.  
  75.  
  76. # -----------------------------
  77. def compile_envar_paths(filename, envar='PATH'):
  78.  
  79.     # envar is short for "operating system environment variable"
  80.  
  81.     '''compile_envar_paths() returns a list of paths
  82.    used by glob.glob() or glob.iglob().
  83.  
  84.    Each path in the list contains the filename to help
  85.    filter out and reduce directory-listing functions
  86.    to only those filenames that match.'''
  87.  
  88.     import os
  89.  
  90.     paths = []
  91.  
  92.     # Allow this program to crash if no PATH environment
  93.     # variable is set.
  94.     # Alternatively we could use os.path.defpath
  95.     # but I'd rather the coder know of such a rare thing
  96.  
  97.     for pth in os.environ[envar].split(os.pathsep):
  98.         # sometimes paths have the added '\' at the end
  99.         # remove '\' or '//' if at end.
  100.         if pth[-1] == os.sep:
  101.             spath = pth + filename + os_wild
  102.         else:
  103.             spath = pth + os.sep + filename + os_wild
  104.         paths.append(spath)
  105.  
  106.     return paths
  107.  
  108.  
  109. # -----------------------------
  110. def icompile_envar_paths(filename, envar='PATH'):
  111.  
  112.     # envar is short for "operating system environment variable"
  113.  
  114.     '''icompile_envar_paths() returns a generator that lists
  115.    paths used by glob.glob() or glob.iglob().
  116.  
  117.    Each path in the list contains the filename to help
  118.    filter out and reduce directory-listing functions
  119.    to only those filenames that match.'''
  120.  
  121.     import os
  122.  
  123.  
  124.     # Allow this program to crash if no PATH environment
  125.     # variable is set.
  126.     # Alternatively we could use os.path.defpath
  127.     # but I'd rather the coder know of such a rare thing
  128.  
  129.     for pth in os.environ[envar].split(os.pathsep):
  130.         # sometimes paths have the added '\' at the end
  131.         # remove '\' or '//' if at end.
  132.         if pth[-1] == os.sep:
  133.             spath = pth + filename + os_wild
  134.         else:
  135.             spath = pth + os.sep + filename + os_wild
  136.         yield spath
  137.  
  138.  
  139.  
  140.  
  141. # -----------------------------
  142. def find(filename, in_paths=None, show=False):
  143.  
  144.     '''Search each glob-like string in in_paths for filename;
  145.    which expects no extension
  146.    if "show" == True print results to stdout
  147.    "show" defaults to False
  148.    returns a list of matching fully qualified filenames
  149.  
  150.    If in_paths is None then find() uses the PATH environment variable.'''
  151.  
  152.     import os
  153.     import glob
  154.  
  155.     if in_paths is None:
  156.         in_paths = compile_envar_paths(filename)
  157.  
  158.     found = []
  159.     for pth in in_paths:
  160.         #print( pth )
  161.         for fn in glob.glob( pth ):
  162.             # ignore directories; << remove this check
  163.             if os.path.isdir(fn): continue
  164.             for ext in runnables:
  165.                 if fn.upper().endswith(ext):
  166.                     found.append(fn)
  167.                     if show:
  168.                         print('%s' % fn)
  169.  
  170.     if len(found) == 0 and show:
  171.         print('File not found.')
  172.  
  173.     return found
  174.  
  175.  
  176.  
  177. # -----------------------------
  178. def ifind(filename, in_paths=None):
  179.  
  180.     '''Search each glob-like string in in_paths for filename;
  181.    which expects no extension.
  182.    This is an iterator that returns each matching
  183.    fully qualified filename.
  184.  
  185.    If in_paths is None then ifind() uses the PATH environment variable.'''
  186.  
  187.     import os
  188.     import glob
  189.  
  190.     if in_paths is None:
  191.         in_paths = icompile_envar_paths(filename)
  192.  
  193.     for pth in in_paths:
  194.         for fn in glob.iglob( pth ):
  195.             # ignore directories; << remove this check?
  196.             if os.path.isdir(fn): continue
  197.             for ext in runnables:
  198.                 if fn.upper().endswith(ext):
  199.                     yield fn
  200.  
  201.  
  202. # -----------------------------
  203. def usage():
  204.     if __name__ == '__main__':
  205.         print('')
  206.         print('inpath will search the PATH for the runnable filename')
  207.         print('')
  208.         print('Run from the command prompt will print the results to stdout.')
  209.         print('Wildcards * and ? are supported before the extension.')
  210.         print('The return order is revelent.')
  211.         print('This script will not find internal commands.')
  212.         print('This script trys to use os envar PATHEXT.')
  213.         print('You many want to see if .py and .pyc are included in PATHEXT.')
  214.         print('')
  215.         print('Sytnax:')
  216.         print('    inpath <filename>')
  217.         print('    C:\\inpath <some-file-name-without-extension-that-is-runnable>')
  218.         print('')
  219.         print('Example syntax:')
  220.         print('    C:\\>python.exe inpath.py net')
  221.         print('    C:\\>inpath python')
  222.         print('    C:\\>inpath pyth*')
  223.         print('    C:\\>inpath pyth?')
  224.         print('    C:\\>inpath python.24')
  225.         print('    C:\\>inpath python2?')
  226.         print('    C:\\>inpath "double quoted file name with space"')
  227.         print('    C:\\>inpath python ignored "extra arguments"')
  228.         print('    C:\\>inpath /h')
  229.         print('A favorite:')
  230.         print('    C:\\>inpath py*')
  231.         print('')
  232.         print('Doing:')
  233.         print('    C:\\>inpath net.exe')
  234.         print('')
  235.         print('will look for:')
  236.         print('    net.exe.com, net.exe.exe, net.exe.bat, etc...')
  237.         print('')
  238.         print('To see usage from within Python interpreter')
  239.         print('    >import inpath')
  240.         print('    >inpath.usage()')
  241.         print('')
  242.     else:
  243.         print """    '''
  244.    # inpath will search the PATH for the runnable filename
  245.  
  246.    # Run from the command prompt will print the results to stdout.
  247.    # Wildcards * and ? are supported before the extension.
  248.    # The return order is revelent.
  249.    # This script will not find internal commands.
  250.  
  251.    # Example syntax:
  252.  
  253.    import inpath
  254.    filename = "pytho*"
  255.    paths = inpath.compile_envar_paths( filename )
  256.    
  257.    found = inpath.find( filename )
  258.    found = inpath.find( filename, paths, show= True )
  259.    found = inpath.find( filename, my_made_paths_list )
  260.    
  261.    from inpath import *
  262.    for found in ifind( 'python' ):
  263.        print( repr( found ) )
  264.    
  265.    
  266.    # To see usage for command line at the command line just type
  267.    "inpath" or "inpath -h"
  268.    '''"""
  269.  
  270. # -----------------------------
  271. if __name__ == '__main__':
  272.  
  273.     import sys
  274.  
  275.     if len(sys.argv) < 2 or sys.argv[1].lower() in help:
  276.         usage()
  277.  
  278.     elif len(sys.argv) >= 2:
  279.         if len(sys.argv) > 2:
  280.             extras = ', '.join([repr(arg) for arg in sys.argv[2:]])
  281.             print('')
  282.             print('These command line arguments are ignored: %s' % extras)
  283.  
  284.         filename = sys.argv[1]
  285.         print('')
  286.         print('Searching in PATH for %s%s:' % (filename, os_wild))
  287.         print('')
  288.         in_paths = compile_envar_paths(filename)
  289.         found = find(filename, in_paths, show=True)
  290.    
  291.  
  292.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement