我的文件夹树:
./
├── README.MD
├── basic
│ └── thresh.py
├── images
│ └── figure.jpg
└── utils
├── util.py
└── util.pyc
我想导入util.py
的thresh.py
:
import sys
sys.path.append('../utils')
import util
当我$ python thresh.py
在basic
文件夹中运行命令时,就可以了。但是$ python ./basic/thresh.py
在最顶层的文件夹中运行,我会得到以下错误:
ImportError:没有名为util的模块
那么如何通过给定文件相对于已执行文件的相对路径来使文件导入$ python ./basic/thresh.py
和$ python thresh.py
工作都可行,而不管python命令路径如何?
您可以获取执行脚本的绝对路径(也有其他变体使用__file__
,但这应该可以工作)
import os
wk_dir = os.path.dirname(os.path.realpath('__file__'))
print( wk_dir )
然后获取它的目录,例如
import sys
sys.path.append(wk_dir+'/../utils')
PS:您可能需要使用__file__
而不是'__file__'
。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句