重新加载模块中的函数 [英] Reloading a function within a module
问题描述
目标
我想从解释器导入一个自定义模块,运行它,修改它,重新加载它,然后再次运行它以查看更改.
背景
我使用的是 python 2.7.在开始编写自己的模块之前,我充分利用了 python 2.7 中的 reload()
函数.
我在一个简单的例子中重现了我的问题
- 我创建了一个文件夹:
demo
- 在
demo
中,我放置了两个文件:__init__.py
和plotme.py
我的 __init__.py
文件包含:
from .plotme 导入图
我的 plotme.py 文件包含:
将 matplotlib.pyplot 导入为 plt将 numpy 导入为 np定义图():x=np.linspace(0,np.pi*4,1000)y=np.cos(x)plt.plot(x,y,'b')
我使用以下命令运行它:
<预><代码>>>>导入演示>>>演示.plot()它工作得很好.
接下来,我决定我希望情节是红色的,而不是蓝色的.我将 plotme.py 中的 'b'
修改为 'r'
并保存.然后我输入:
并且情节仍然是蓝色,而不是红色.不是我想要的.相反,我尝试:
<预><代码>>>>重新加载(演示)>>>演示.plot()再说一次,颜色没有更新.
我认为 \__init__.py
中需要有一个重新加载命令.我尝试将其更新为:
from .plotme 导入图重新加载(情节)
当我输入时:
<预><代码>>>>重新加载(演示)我收到错误:
TypeError: reload() 参数必须是模块
我改为尝试使用 reload(.plotme)
重新加载.同样的错误.当我尝试 reload(plotme)
时,它不会抛出错误,但绘图的颜色不会更新为红色.
我该如何解决这个问题?
我不希望每次修改几行代码时都不必关闭并重新启动解释器.
您必须重新加载 demo
模块(即文件 demo/__init__.py)**和**文件
demo/plotme.py即
demo.plotme.更准确地说,当您从
plotme 子模块导入
plot函数时,您必须先导入
plotme然后
demo`:
reload(demo.plotme)重新加载(演示)
在这两个命令之后,plotme 中的任何更改都将被考虑在内.
Goal
I would like to import a custom module from the interpreter, run it, modify it, reload it, and run it again to see the changes.
Background
I'm using python 2.7. Before I started writing my own modules, I made great use of the reload()
function in python 2.7.
I reproduced my issue in a simple example
- I create a folder called:
demo
- Inside
demo
, I place two files:__init__.py
andplotme.py
My __init__.py
file contains:
from .plotme import plot
My plotme.py file contains:
import matplotlib.pyplot as plt
import numpy as np
def plot():
x=np.linspace(0,np.pi*4,1000)
y=np.cos(x)
plt.plot(x,y,'b')
I run it with the commands:
>>> import demo
>>> demo.plot()
and it works just fine.
Next, I decide that I want the plot to be red, not blue. I modify 'b'
to 'r'
in plotme.py and save. I then type:
>>> import(demo)
>>> demo.plot()
and the plot is still blue, not red. Not what I want. Instead I try:
>>> reload(demo)
>>> demo.plot()
and again, the color has not updated.
I figure that there needs to be a reload command inside \__init__.py
. I try updating it to:
from .plotme import plot
reload(plot)
and when I type:
>>> reload(demo)
I get the error:
TypeError: reload() argument must be module
I instead try reloading with reload(.plotme)
. Same error. When I try reload(plotme)
, it doesn't throw an error, but the color of the plot isn't updating to red.
How do I fix this?
I would prefer not to have to close and relaunch the interpreter every time I modify a few lines of code.
You must reload both demo
module (i.e. the file demo/__init__.py) **and** the file
demo/plotme.pywhich is
demo.plotme. More precisely, as you import
plotfunction from the
plotmesub module, you must import first
plotmeand then
demo`:
reload(demo.plotme)
reload(demo)
After those 2 commands, any changes in plotme will be taken into account.
这篇关于重新加载模块中的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!