问题描述
下面是我的项目结构。
├── folder1
├── test.py
├── folder2
├── A.py
├── folder3
├── A.py
A.py
和 folder2
中的 folder3
是相同的,除了 self.key
#folder2
class TestAPI():
def __init__(self):
self.key = 50
#folder3
class TestAPI():
def __init__(self):
self.key = 100
在test.py
中,代码是
import sys
root_path = '/user/my_account'
sys.path.insert(0,root_path + '/folder2')
from A import TestAPI
test_api = TestAPI()
print(test_api.key)
sys.path.insert(0,root_path + '/folder3')
from A import TestAPI
test_api = TestAPI()
print(test_api.key)
print(sys.path)
在执行 test.py
时,它返回 50
、50
、['/user/my_account/folder3','/user/my_account/folder2']
。为什么第二次 from A import TestAPI
不是来自 folder3
而是 folder2
?
编辑:如果我想第二次从 import TestAPI
中 folder3
,有没有办法从 PYTHONPATH
中“删除”import TestAPI
之后的 folder2
1}}?
解决方法
我会将您的 TestAPI
代码 (A.py) 更改为公共文件夹(可以通过其他代码导入的文件夹),然后:
class TestAPI():
def __init__(self,key):
self.key = key
然后在您的 test.py 中,您可以执行以下操作:
import sys
root_path = '/user/my_account'
sys.path.insert(0,root_path + '/commons')
from commons.A import TestAPI
test_api_50 = TestAPI(50)
print(test_api_50.key)
test_api_100 = TestAPI(100)
print(test_api_100.key)
如果有问题/错别字,我可以编辑它。
请注意,python 文件夹/包装值得一读。你未来的自己会感谢你。
,importlib.reload
解决我的问题。
import sys
root_path = '/user/my_account'
sys.path.insert(0,root_path + '/folder2')
import A
test_api = A.TestAPI()
print(test_api.key)
sys.path.insert(0,root_path + '/folder3')
import importlib
importlib.reload(A) # should reload after inserting PYTHONPATH and before import A
import A
test_api = A.TestAPI()
print(test_api.key)
print(sys.path)
,
sys.path 是一个列表。所以只需使用 append 方法。
此外,您不需要根路径。就跑
sys.path.append('folder2')
编辑:证明它有效的演示
[luca@artix stackoverflow]$ mkdir my_module
[luca@artix stackoverflow]$ ed my_module/foo.py
?my_module/foo.py
i
print('From foo')
.
wq
18
[luca@artix stackoverflow]$ python
Python 3.9.1 (default,Feb 6 2021,13:49:29)
[GCC 10.2.0] on linux
Type "help","copyright","credits" or "license" for more information.
>>> import foo
Traceback (most recent call last):
File "<stdin>",line 1,in <module>
ModuleNotFoundError: No module named 'foo'
>>> import sys
>>> sys.path.append('my_module')
>>> import foo
From foo
>>>