python .pth 文件 和 site 模块


.pth 文件

该文件位于 python 的 /Lib/site-packages 目录下, 可以有多个 ,在 .pth 文件中可以把其它目录添加到 sys.path 中,可以是相对路径和绝对路径,例如:

注释只能单独一行,以#开头

绝对路径

d:/testPth

当前目录相对路径,有两种方式,以 /Lib/site-packages 为基目录

testPth

./testPth2

上级目录

../../testParentPth

在 pth 文件中,还可以添加 python 代码,注意的是完整的代码要在一行当中,隔行不行, 而且要以 import 开头 ,例如:

import os

print(os)

上面是打印不出 os 的路径的,正确的做法是:

import os;print(os);import sys;print(sys.executable)

import os;print(os.path)

在 .pth 文件中,有个变量 sitedir,这个变量代表 /Lib/site-packages 的绝对路径

site 模块和 .pth

知道 .pth 的用法后,我们可以添加一个自定义的 .pth ,再配置我们额外的 site-packages

在 .pth 中添加行:

import site;site.addsitedir('<your-custom-sitedir>')

添加自定义的 sitedir 后,python 会自动执行该目录下的所有 .pth

在代码中运行 site.addsitedir 后,也会运行带 import 开头的行。


原文链接:https://www.cnblogs.com/ibingshan/p/11082510.html