【问题标题】:How to add a Python import path using a .pth file如何使用 .pth 文件添加 Python 导入路径
【发布时间】:2010-10-16 13:38:40
【问题描述】:

如果我将 *.pth 文件放在站点包中,它会给出 ImportError。 我不知道如何通过创建 *.pth 文件来导入。

(参考importing in python

【问题讨论】:

标签: python python-import


【解决方案1】:

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

K:\Source\Python\lib

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

logger.py
fstools.py
...

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

import logger

log = logger.Log()
...

【讨论】:

  • 短小精悍... :-)
  • 但是你把 sth.pth 文件放在哪里呢?当 python 安装在 C:\python27 中时?
  • 谢谢,我用过import syssys.path.append(path) 有一段时间了。这行得通
【解决方案2】:
/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']

【讨论】:

  • 请简要说明您在做什么
猜你喜欢
  • 1970-01-01
  • 2012-05-18
  • 2015-07-28
  • 1970-01-01
  • 2017-09-11
  • 2021-12-30
  • 2018-10-11
  • 2015-10-30
  • 1970-01-01
相关资源
最近更新 更多