![](/img/trans.png)
[英]How to import a class from a different package in the present package in python?
[英]import class from different python package
我檢查了很多關於SO的問題,但無法解決。
我有一個像這樣的python結構:
test_env/
|A/
| |__init__.py
| |lib/
| |abc.py
| |__init__.py
|lib/
| |file1.py #this has a class MyClass
| |__init__.py
|test/
| |test.py #executing this file
我的PYTHONPATH:
export PYTHONPATH="${PYTHONPATH}:/Users/username/test_env/A/lib/:/Users/username/test_env/lib"
test_env / test / test.py
from abc import some_function
from lib.file1 import MyClass
-----
出現錯誤: ImportError: No module named abc
並且No module named lib.file1
注意:我使用的是pyCharm,當我from abc import some_function
鍵入內容時,便可以找到上述模塊。 有什么建議么 ?
我不確定這是否是拼寫錯誤,但您的文件結構是'/ Users / username / test_env / A / lib /'而不是'/ Users / username / test / A / lib /'
如果仍不能解決問題,則可以在test_env / test / test.py文件的開頭嘗試以下操作:
sys.path.append('/Users/username/test_env/A/lib/')
sys.path.append('/Users/username/test_env/lib/')
from abc import some_function
from file1 import MyClass
它僅針對您正在處理的腳本,將字符串顯式添加到PATH變量中。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.