为什么 sys.path.insert 不使用最新的 python 包?

问题描述

下面是我的项目结构。

├── folder1
    ├── test.py
├── folder2
    ├── A.py
├── folder3
    ├── A.py
A.pyfolder2 中的

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 时,它返回 5050['/user/my_account/folder3','/user/my_account/folder2']。为什么第二次 from A import TestAPI 不是来自 folder3 而是 folder2

编辑:如果我想第二次从 import TestAPIfolder3,有没有办法从 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
>>> 

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...