【发布时间】:2021-05-13 23:52:18
【问题描述】:
我正在尝试创建一个像在线法官一样的 leetcode。我需要重新加载提交模块,但import.reload() 不起作用。
代码:
class Test:
current_exercise = None
current_name = None
def _import(self, exercise):
exercise = 'exercise' # for testing
if exercise == self.current_name:
module = sys.modules[f'puzzles.{exercise}']
self.current_exercise = importlib.reload(module) # <---- not working
else:
self.current_name = exercise
self.current_exercise = __import__(f'puzzles.{exercise}').exercise
def _test(self, exercise):
solution = self._import(exercise)
print(self.current_exercise.main())
if __name__=='__main__':
import shutil
t= Test()
# first run
t._test('exercise')
# copy another solution.py for reload test
shutil.copy(f"./puzzles/other_exercise/solution.py", f"./puzzles/exercise/solution.py")
# second run
t._test('exercise')
我的目录;
.
├── codetest.py
├── puzzles
│ ├── __init__.py
│ ├── exercise
│ │ ├── __init__.py
│ │ ├── solution.py
│ ├── other_exercise
│ │ ├── __init__.py
│ │ ├── solution.py
练习/solution.py:
def main():
print('EXERCISE')
练习/初始化.py
>from .solution import main
from .test import cases
other_exercise/solution.py:
def main():
print('OTHER EXERCISE')
输出:
> EXERCISE
> EXERCISE # <--- not sucessfull, should be 'OTHER EXERCISE'
【问题讨论】:
-
.p0在您的__import__行末尾做什么? -
其他方式都行不通。
-
有趣。您的
__init__.py文件中有什么内容?除非有人导入了solution,否则main()将不可用。 -
一个有用的提示:您应该将不推荐的
__import__替换为importlib.import_module(f"puzzles.{exercise}")。它没有解决根本问题,但确实消除了对额外.exercise后缀的需要。 -
问题似乎是重新导入“puzzles/exercise”对重新导入solutions.py没有任何作用。如果您将重新导入行更改为
self.current_exercise.solution = importlib.reload(self.current_exercise.solution),那么它可以工作。
标签: python python-3.x python-importlib