Python reboot module does not take effect immediately

see below play code.

Tracking a memory leak, I found that a reboot (module) did not immediately take effect.

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

Please note that this code is its own version of more practical code. In order to reproduce the problem, I need to deal with the situation in a real application.

Does anyone have any ideas on 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)
+3
source share
1 answer

The problem is that pyc will not regenerate unless it is deprecated relative to the py initialization file. If the file modification time is checked with a resolution of one second, your updates are likely to be ignored and an outdated pyc is called, not your updated source.

  • pyc .

  • PYTHONDONTWRITEBYTECODE=1.

  • , execfile.

+4

All Articles