tags:

views:

296

answers:

2
+1  Q: 

delete *.pyc

I have three modules as:

one.py:

def abc():
    print "Heeeeeeeeeeeiiiiiioooooooooo"

two.py:

import one

def defg():
    one.abc()

three.py:

import os
from time import sleep

import two
two.defg()

sleep(20)


directory = os.listdir('.')

for filename in directory:
    if filename[-3:] == 'pyc':
     print '- ' + filename
     os.remove(filename)

I have three doubts.Kindly help me.

When i run three.py for the first time one.pyc and two.pyc will be created. I can see it since i gave 20 sec delay. After executing the statement os.remove(filename), they gets removed. Until here its fine.

Again without closing the IDLE as well as script i ran three.py. This time no .pyc file was created. Why is this so ?

If I close IDLE as well as the script, .pyc will be created as before.

Why the compiled code is not getting created again and agin ?

Also,if I make a change in one.py it will not be shown if I run without closing the shells. I need a solution for this also.

Third doubt is if the compiled code is getting deleted first time itself then how the second run gives the same result without .pyc?

Hoping for a solution...

+1  A: 

I think that IDLE is caching the bytecode within its own Python process, so it doesn't need to regenerate the it each time the file is run.

mikl
Hmm, yes, what Nathan said :)
mikl
thank you for the solution
+8  A: 

The .pyc isnt getting created again because there is a refernce to your imported module in code. When it is re-run, this reference is used.

This is why the .pyc isnt generated again, and also why the extra changes you make arent getting run.

You can either remove all references and call a garbage collect, or use the built in reload() function on the modules. e.g.:

reload(three)
Nathan Ross Powell
Thank you. So when the shell is closed new reference comes to play ?Anyway I want to avoid reload() How to remove all references and call a garbage collect ?
sys.modules always retains a reference, so you can't cause a module to go away like that, short of manually fiddling sys.modules, which is fraught with difficulty. See http://stackoverflow.com/questions/437589/how-do-i-unload-reload-a-python-module
bobince
How i have done things before, not claiming the best implementation. import three; import sys,gc; del three # remove the local reference; del sys.modules["three"] # removes import; gc.collect() # make sure everythings tidyed up; import three # new .pyc
Nathan Ross Powell
it was a good implementation...Thank you Sir