DevPlayer

inpath

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