简介
用Python在Windows下模仿Linux的|which.exe|程序。
这个程序会从Windows环境变量|PATH|里列出的所有目录中查找"可执行文件"。
在Linux下|which.exe|通过文件的"可执行"属性来判断文件是否可执行不同。
在Windows下我们通过扩展名来判断。
如果一个文件的扩展名是|.exe|, |.bat|,或者任何在Windows环境变量|PATHEXT|中列出的扩展名(比如我们自己添加的|.py|),则认为这个文件为"可执行文件"。这个定义也符合Windows的CMD对"可执行文件"的定义。
源码
闲话少说,先上源码。实现的具体分析见源码中注释及源码后的分析。
__doc__ = """
Author: kuiyuyou@gmail.com
File: aoiwhich.py
"""
import sys
import os
def find_executable(program):
""" Given |program| which is the name or path of a program, find a list of
executable paths of the program.
#// Arguments
program: the name or path of a program. No need to include extension.
return: a list of executable paths of the program.
#// What an "executable" means?
An executable means an existing file whose extension is |.exe|, |.bat|, or
any other extensions listed in Windows environment variable |PATHEXT|.
#// What is the algorithm used to find all the executable paths?
Use each of dir paths listed in Windows environment variable |PATH| as parent dir.
Use each of extensions listed in Windows environment variable |PATHEXT| as extension.
Synthesize all the possible paths by combining each parent dir, the |program| given,
and each extension. (Empty parent dir and empty extension are two special cases.