python重新加载模块_Python重新加载模块不会立即生效

see the reproduction code below.

Tracing a memory leak I found that reload(module) does not immediately take effect.

The program below should print 0,1,2,3,4 but, when executed fast it prints sequences like 0,0,0,3,3 and such. Increasing the time in the sleep() function to eg 1 second seems to fix this.

Note that this code is a boiled down version of more practical code just to reproduce the problem, I need to deal with a situation in a real life app.

Does anybody have an idea how to ensure stability?

I'm on windows, cpython27 32 bit.

Thanks for reading this.

# this program assumes folder lib\mymodule exists and contains __init__.py

import time

import io

import gc

modulefile = 'c:\\python27\\lib\\mymodule\\simplemodule.py'

for cnt in range(5):

modulecode = """def runmodule():

return %i

"""%(cnt)

obj = io.open(modulefile, u'wb')

obj.write(modulecode)

obj.close()

if cnt==0:

import mymodule.simplemodule

else:

reload(mymodule.simplemodule)

gc.collect()

print mymodule.simplemodule.runmodule()

time.sleep(0.05)

解决方案

The problem is that a pyc won't regenerate unless it is out-of-date with respect to the undelying py file. If the file modification times are checked with a one second resolution, your updates are likely being ignored and the out-of-date pyc is invoked rather than your updated source.

Try removing the pyc file between each import or reload.

Alternatively, you can the set the environment variable PYTHONDONTWRITEBYTECODE=1.

You can also bypass the import logic by using execfile.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值