导入前确定Python包位置

Ian*_*nSR 6 python import path

我想导入之前获取包的位置.基本上我想做

import pkg
pkg_path = pkg.__file__
Run Code Online (Sandbox Code Playgroud)

但不必import pkg.现在我正在做:

target = "pkg"
target_path = None
for p in sys.path:
    search_path = "%s/%s" % (p, target)
    if os.path.exists(search_path):
        target_path = search_path
Run Code Online (Sandbox Code Playgroud)

但有几种情况下这不起作用(target不包含__init__.py,target在压缩的EGG文件中).

有没有更好的方法target_path

谢谢,

伊恩

Sve*_*ach 5

是的,有imp.find_module():

target_path = imp.find_module(target)
Run Code Online (Sandbox Code Playgroud)