python:defer_to_another_program_in_the_path_if_available
no way to compare when less than two revisions
Differences
This shows you the differences between two versions of the page.
— | python:defer_to_another_program_in_the_path_if_available [2012/08/29 08:43] (current) – created tkbletsc | ||
---|---|---|---|
Line 1: | Line 1: | ||
+ | ====== Defer to another program in the PATH if available ====== | ||
+ | Let's say you want a custom replacement for a program on systems that don't have it, but you want to use the native binary on systems that do. Let's further assume that you want to put one file in your path everywhere and have it do the right thing (for example, if you're sharing an NFS home directory between diverse machines). | ||
+ | |||
+ | < | ||
+ | # | ||
+ | |||
+ | import os,sys | ||
+ | |||
+ | # return an array of elements from the PATH environment varible (cross-platform) | ||
+ | def get_sys_path(): | ||
+ | if sys.platform == ' | ||
+ | return os.environ[' | ||
+ | else: | ||
+ | return os.environ[' | ||
+ | |||
+ | # find all executable binaries in the PATH environment variable with the given name, adding " | ||
+ | def find_all_in_path(filename): | ||
+ | filename = os.path.basename(filename) | ||
+ | def isexec(p): return os.path.isfile(p) and os.access(p, | ||
+ | is_win = sys.platform in (' | ||
+ | r=[] | ||
+ | for path in get_sys_path(): | ||
+ | t = os.path.join(path, | ||
+ | if isexec(t): | ||
+ | r.append(t) | ||
+ | elif is_win and not t.endswith(' | ||
+ | r.append(t+' | ||
+ | return r | ||
+ | |||
+ | # find all the other programs with the same name as this one in the path, return as an array | ||
+ | def find_other_matching_programs(filename=None): | ||
+ | if not filename: filename = sys.argv[0] | ||
+ | if ' | ||
+ | samefile = os.path.samefile | ||
+ | else: | ||
+ | samefile = lambda a,b: os.path.abspath(a) == os.path.abspath(b) # Windows fallback | ||
+ | return [t for t in find_all_in_path(filename) if not samefile(filename, | ||
+ | |||
+ | # if there' | ||
+ | def defer_to_other_program(): | ||
+ | m = find_other_matching_programs() | ||
+ | if m: | ||
+ | os.execv(m[0], | ||
+ | |||
+ | """ | ||
+ | def get_sys_path_unix(): | ||
+ | return os.environ[' | ||
+ | |||
+ | def find_all_in_path_unix(filename): | ||
+ | return [t for t in (os.path.join(path, | ||
+ | |||
+ | def find_other_matching_programs_unix(filename=None): | ||
+ | if not filename: filename = sys.argv[0] | ||
+ | return [t for t in find_all_in_path(filename) if not os.path.samefile(filename, | ||
+ | """ | ||
+ | |||
+ | defer_to_other_program() | ||
+ | </ | ||
+ | |||
+ | If you wanted to build a wrapper out of this, just put what you want to happen if the app is missing after the '' |
python/defer_to_another_program_in_the_path_if_available.txt · Last modified: 2012/08/29 08:43 by tkbletsc