17

如果我将 *.pth 文件放在站点包中,它会给出一个 .pth 文件ImportError。我没有通过创建 *.pth 文件来了解如何导入。

(指在python中导入

4

2 回答 2

39

如果您将.pth文件放在site-packages包含路径的目录中,python 会在此路径中搜索导入。所以我有一个sth.pth文件,其中只包含:

K:\Source\Python\lib

在那个目录中有一些普通的 Python 模块:

logger.py
fstools.py
...

这允许直接从其他脚本导入这些模块:

import logger

log = logger.Log()
...
于 2009-03-31T07:23:40.290 回答
27
/tmp/$ mkdir test; cd test
/tmp/test/$ mkdir foo; mkdir bar
/tmp/test/$ echo -e "foo\nbar" > foobar.pth
/tmp/test/$ cd ..
/tmp/$ python
Python 2.6 (r26:66714, Feb  3 2009, 20:52:03)
[GCC 4.3.2 [gcc-4_3-branch revision 141291]] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import site, sys
>>> site.addsitedir('test')
>>> sys.path[-3:]
['/tmp/test', '/tmp/test/foo', '/tmp/test/bar']
于 2009-03-31T08:11:16.570 回答