Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # DevPlayer@gmail.com
- # 2011-Oct-06
- # License: LGPL
- # Python 2.7
- # inpath.py
- # revision 0.9.0-beta
- # TO DO:
- # test with no PATHEXT and or no PATH environment variables
- # fix for on Mac and linux/unix
- import os
- import sys
- import glob
- '''Find a runnable program in PATH or supplied list of paths.
- Search the PATH environment variable for all runnable
- file names that match. Wildcards are not supported.
- If at the DOS prompt you type "somecommand" and it runs
- you may not know where in the PATH that program is and or
- what file name extension the "somecommand" has.
- This tool will find it.'''
- help = ['-h', '--h', '-help', '--help', '/h', '/help']
- # -----------------------------
- # prep the running environment
- if True: # <- my-trick-to-force-editor-block-folding
- # - - - - - - - - - - - -
- # Microsoft usually has an environment variable PATHEXT
- if os.environ.has_key('PATHEXT'):
- # remove dups from runnables extension list;
- _runnables = [ext for ext in os.environ['PATHEXT'].split(os.pathsep)]
- runnables = []
- # Remember that NOT all extensions are
- # ".xxx" chars long. And some filenames are like
- # myfile.someext.someother_ext.ext
- for ext in _runnables:
- if ext not in runnables:
- runnables.append(ext)
- del _runnables, ext
- else: # No PATHEXT found
- if sys.platform == 'win32':
- runnables = ['.COM', '.EXE', '.BAT']
- else:
- # Unix/Linux does not have that requirement
- runnables = []
- # - - - - - - - - - - - -
- # The wild card is different on different OSes
- # This script presumes MS and linux wildcards
- # I don't know Mac wildcards
- if sys.platform == 'win32':
- os_wild = '.*'
- else:
- os_wild = '*'
- # -----------------------------
- def compile_envar_paths(filename, envar='PATH'):
- # envar is short for "operating system environment variable"
- '''compile_envar_paths() returns a list of paths
- used by glob.glob() or glob.iglob().
- Each path in the list contains the filename to help
- filter out and reduce directory-listing functions
- to only those filenames that match.'''
- import os
- paths = []
- # Allow this program to crash if no PATH environment
- # variable is set.
- # Alternatively we could use os.path.defpath
- # but I'd rather the coder know of such a rare thing
- for pth in os.environ[envar].split(os.pathsep):
- # sometimes paths have the added '\' at the end
- # remove '\' or '//' if at end.
- if pth[-1] == os.sep:
- spath = pth + filename + os_wild
- else:
- spath = pth + os.sep + filename + os_wild
- paths.append(spath)
- return paths
- # -----------------------------
- def icompile_envar_paths(filename, envar='PATH'):
- # envar is short for "operating system environment variable"
- '''icompile_envar_paths() returns a generator that lists
- paths used by glob.glob() or glob.iglob().
- Each path in the list contains the filename to help
- filter out and reduce directory-listing functions
- to only those filenames that match.'''
- import os
- # Allow this program to crash if no PATH environment
- # variable is set.
- # Alternatively we could use os.path.defpath
- # but I'd rather the coder know of such a rare thing
- for pth in os.environ[envar].split(os.pathsep):
- # sometimes paths have the added '\' at the end
- # remove '\' or '//' if at end.
- if pth[-1] == os.sep:
- spath = pth + filename + os_wild
- else:
- spath = pth + os.sep + filename + os_wild
- yield spath
- # -----------------------------
- def find(filename, in_paths=None, show=False):
- '''Search each glob-like string in in_paths for filename;
- which expects no extension
- if "show" == True print results to stdout
- "show" defaults to False
- returns a list of matching fully qualified filenames
- If in_paths is None then find() uses the PATH environment variable.'''
- import os
- import glob
- if in_paths is None:
- in_paths = compile_envar_paths(filename)
- found = []
- for pth in in_paths:
- #print( pth )
- for fn in glob.glob( pth ):
- # ignore directories; << remove this check
- if os.path.isdir(fn): continue
- for ext in runnables:
- if fn.upper().endswith(ext):
- found.append(fn)
- if show:
- print('%s' % fn)
- if len(found) == 0 and show:
- print('File not found.')
- return found
- # -----------------------------
- def ifind(filename, in_paths=None):
- '''Search each glob-like string in in_paths for filename;
- which expects no extension.
- This is an iterator that returns each matching
- fully qualified filename.
- If in_paths is None then ifind() uses the PATH environment variable.'''
- import os
- import glob
- if in_paths is None:
- in_paths = icompile_envar_paths(filename)
- for pth in in_paths:
- for fn in glob.iglob( pth ):
- # ignore directories; << remove this check?
- if os.path.isdir(fn): continue
- for ext in runnables:
- if fn.upper().endswith(ext):
- yield fn
- # -----------------------------
- def usage():
- if __name__ == '__main__':
- print('')
- print('inpath will search the PATH for the runnable filename')
- print('')
- print('Run from the command prompt will print the results to stdout.')
- print('Wildcards * and ? are supported before the extension.')
- print('The return order is revelent.')
- print('This script will not find internal commands.')
- print('This script trys to use os envar PATHEXT.')
- print('You many want to see if .py and .pyc are included in PATHEXT.')
- print('')
- print('Sytnax:')
- print(' inpath <filename>')
- print(' C:\\inpath <some-file-name-without-extension-that-is-runnable>')
- print('')
- print('Example syntax:')
- print(' C:\\>python.exe inpath.py net')
- print(' C:\\>inpath python')
- print(' C:\\>inpath pyth*')
- print(' C:\\>inpath pyth?')
- print(' C:\\>inpath python.24')
- print(' C:\\>inpath python2?')
- print(' C:\\>inpath "double quoted file name with space"')
- print(' C:\\>inpath python ignored "extra arguments"')
- print(' C:\\>inpath /h')
- print('A favorite:')
- print(' C:\\>inpath py*')
- print('')
- print('Doing:')
- print(' C:\\>inpath net.exe')
- print('')
- print('will look for:')
- print(' net.exe.com, net.exe.exe, net.exe.bat, etc...')
- print('')
- print('To see usage from within Python interpreter')
- print(' >import inpath')
- print(' >inpath.usage()')
- print('')
- else:
- print """ '''
- # inpath will search the PATH for the runnable filename
- # Run from the command prompt will print the results to stdout.
- # Wildcards * and ? are supported before the extension.
- # The return order is revelent.
- # This script will not find internal commands.
- # Example syntax:
- import inpath
- filename = "pytho*"
- paths = inpath.compile_envar_paths( filename )
- found = inpath.find( filename )
- found = inpath.find( filename, paths, show= True )
- found = inpath.find( filename, my_made_paths_list )
- from inpath import *
- for found in ifind( 'python' ):
- print( repr( found ) )
- # To see usage for command line at the command line just type
- "inpath" or "inpath -h"
- '''"""
- # -----------------------------
- if __name__ == '__main__':
- import sys
- if len(sys.argv) < 2 or sys.argv[1].lower() in help:
- usage()
- elif len(sys.argv) >= 2:
- if len(sys.argv) > 2:
- extras = ', '.join([repr(arg) for arg in sys.argv[2:]])
- print('')
- print('These command line arguments are ignored: %s' % extras)
- filename = sys.argv[1]
- print('')
- print('Searching in PATH for %s%s:' % (filename, os_wild))
- print('')
- in_paths = compile_envar_paths(filename)
- found = find(filename, in_paths, show=True)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement