[英]How do I import an object from main.py (in the root directory), into a module contained in a subdirectory?
[英]How do I import from a subdirectory?
這是復雜項目中存在的問題的簡化。 在一個名為root_test
的文件夾中,我有一個名為test
的文件夾,其中包含tester.py
。 我(在test
)還有一個modules
目錄(空),其中包含一個lib
目錄,該目錄包含logger.py
。 目錄結構如下。
|-root_test
|---test/
|-----tester.py
|-----__init__.py
|-----modules/
|-------__init__.py
|-------lib/
|---------__init__.py
|---------logger.py
或者,從root_test
運行:
$ ls
test
$ ls test/
__init__.py modules tester.py
$ ls test/modules/
__init__.py lib
$ ls test/modules/lib/
__init__.py logger.py
tester.py
如下:
#!/usr/bin/env python
import sys, os
# allow running without installing
sys.path.append(os.path.join(os.path.dirname(os.path.realpath(__file__)), '..'))
import test.modules.lib.logger
但是當我嘗試從root_test
目錄運行它時, root_test
以下錯誤:
$ python test/tester.py
Traceback (most recent call last):
File "test/tester.py", line 8, in <module>
import test.modules.lib.logger
ImportError: cannot import name logger
這在我的其他筆記本電腦上不會發生,它們的$PYTHONPATH
相同:
$ echo $PYTHONPATH
/usr/local/lib/python2.7/dist-packages/:/usr/local/lib/python2.7/site-packages/:
解決的辦法是安裝一個名為tester的模塊。 即使我顯式運行python ~/test/tester.py
,它仍然會運行已安裝的模塊。 卸下該模塊可解決此問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.