kingforce 发表于 2018-8-14 11:40:06

python 如何引用上级目录的模块

  今天,做一个测试,想在当前python中引用上层目录的模块;呃,一番搜索。
  先看一下目录情况:
# tree  
.
  
├── t1.py
  
├── t2
  
│   └── t2.py
  
└── xxu
  
    └── test.py
  

  
2 directories, 3 files
  其实,最开始仅仅是想,test.py中可以调用t1.py中函数:
  直接使用的效果:
# cat test.py  
#/usr/bin/env python
  
#coding:utf-8
  

  
import t1
  

  
print t1.t1()
  
# python test.py
  
Traceback (most recent call last):
  
File "test.py", line 4, in <module>
  
    import t1
  
ImportError: No module named t1
  一番搜索以后,发现原理就是,通过os.path.append("路径")的方式,将python的环境变量切换到上一级,就可以直接引用t1模块了
# cat test.py  
#/usr/bin/env python
  
#coding:utf-8
  
import sys
  
sys.path.append("/test/test")
  
import t1
  
print t1.t1()
  
# python test.py
  
t1 test
  必须使用绝对路径
  第二种扩展:
  就是通过test.py调用t2.py中的函数
  原理就是在t2目录中创建一个空文件__init__.py,这样python就识别t2这个目录是一个包,不然就仅仅为目录
# tree  
.
  
├── t1.py
  
├── t1.pyc
  
├── t2
  
│   ├── __init__.py
  
│   └── t2.py
  
└── xxu
  
    └── test.py
  

  
2 directories, 5 files
# cat ../t2/t2.py  
#/usr/bin/env python
  
#coding:utf-8
  

  
def t2():
  
    print "t2 test!!!"
  
# vim test.py
  
# python test.py
  
t1 test
  
t2 test!!!
  
None
页: [1]
查看完整版本: python 如何引用上级目录的模块