7.1让你的模块可用
- 将模块放置在正确的位置,可用下面的函数查看“正确的位置”
>>> pprint.pprint(sys.path)
['',
'/home/xx/$PYTHONPATH',
'/usr/lib/python35.zip',
'/usr/lib/python3.5',
'/usr/lib/python3.5/plat-x86_64-linux-gnu',
'/usr/lib/python3.5/lib-dynload',
'/usr/local/lib/python3.5/dist-packages',
'/usr/lib/python3/dist-packages']
注意:将自己的包/模块 放入到这些个目录中,即可用。
- 告诉编译器去哪里找,貌似这是更加通用的做法
- 编辑sys.path: 这是一种临时配置的方式,再次打开python的时候路径掉了。
>>> import flash
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: No module named 'flash'
>>> sys.path.append('/home/xx/Codes/eclipse/pythonbook/xx/')
>>> pprint.pprint(sys.path)
['',
'/home/xx/$PYTHONPATH',
'/usr/lib/python35.zip',
'/usr/lib/python3.5',
'/usr/lib/python3.5/plat-x86_64-linux-gnu',
'/usr/lib/python3.5/lib-dynload',
'/usr/local/lib/python3.5/dist-packages',
'/usr/lib/python3/dist-packages',
'/home/xx/Codes/eclipse/pythonbook/xx/']
>>> import flash
>>> flash.flashprint('beauty')
Flash Print: beauty
- 标准的方法是:编辑PYTHONPATH环境变量,设置方法链接
sudo gedit /etc/environment # Terminal 打开环境变量文件
export PYTHONPATH=$PYTHONPATH:/home/xx/Codes/eclipse/pythonbook/xx/ # 文件中增加PYTHONPATH值
source /etc/environment # Terminal 中使之生效
效果是:
>>> pprint.pprint(sys.path)
['',
'/home/xx/$PYTHONPATH',
'/home/xx/Codes/eclipse/pythonbook/xx',
'/usr/lib/python35.zip',
'/usr/lib/python3.5',
'/usr/lib/python3.5/plat-x86_64-linux-gnu',
'/usr/lib/python3.5/lib-dynload',
'/usr/local/lib/python3.5/dist-packages',
'/usr/lib/python3/dist-packages']
>>> flash.flashprint('beauty')
Flash Print: beauty
- pth文件
我的文件树结构如下
├── pythonbook
│ ├── xx
│ │ ├── flash.py
│ └── yy
│ ├── conf.pth
│ └── test.py
conf.pth 内容
/home/xx/Codes/eclipse/pythonbook/xx/
test.py 内容
print('YY is outputting')
import flash
flash.flashprint('beauty')
- 直接运行test.py报错,可是我明明在pth文件中指明了flash.py的路径呀。尽管当前文件夹('')是python编译器查找的路径,但还是需要将pth文件放到别的编译器能够查找的位置,比如'/usr/lib/python3/dist-packages'。这样直接可以import该模块了(不存在路径问题)。
>>> pprint.pprint(sys.path)
['',
'/usr/lib/python35.zip',
'/usr/lib/python3.5',
'/usr/lib/python3.5/plat-x86_64-linux-gnu',
'/usr/lib/python3.5/lib-dynload',
'/usr/local/lib/python3.5/dist-packages',
'/usr/lib/python3/dist-packages']