3 回答

TA贡献1874条经验 获得超12个赞
一般来说,我认为搜索程序路径并不是一个好主意。想象一下,例如,机器上安装了两个不同的版本。您确定要找到合适的吗?用标准模块ConfigParser解析的配置文件也许是更好的选择?
无论如何,回到您的问题,为了找到文件或目录,您可以尝试使用os.walk,它以递归方式遍历目录树。
这是一个os.walk从生成器调用的示例,允许您收集第一个或所有匹配的文件名。请注意,生成器结果仅基于文件名。如果您需要更高级的过滤(例如,仅保留可执行文件),则可能会使用os.stat()之类的东西来扩展测试。
import os
def fileInPath(name, root):
for base, dirs, files in os.walk(root):
if name in files:
yield os.path.join(base, name)
print("Search for only one result:")
print(next(fileInPath("python", "/home/sylvain")))
print("Display all matching files:")
print([i for i in fileInPath("python", "/home/sylvain")])

TA贡献1835条经验 获得超7个赞
有一个名为Unipath的软件包,可以执行简洁,干净的路径计算。
在这里寻找AbstractPath构造函数
例子:
from unipath import Path
prom_dir = Path(__file__)

TA贡献1898条经验 获得超8个赞
有which
Linux和where
适用于Windows。它们都为您提供了可执行文件的路径,前提是该文件位于控制台“搜索”的目录中(因此,对于Windows,它必须位于%PATH%中)。
添加回答
举报