Вопрос

I have written a rather large module which is automatically compiled into a .pyc file when I import it.

When I want to test features of the module in the interpreter, e.g., class methods, I use the reload() function from the imp package.

The problem is that it reloads the .pyc file, not the .py file.

For example I try a function in the interpreter, figure out that it is not working properly, I would make changes to the .py file. However, if I reload the module in the interpreter, it reloads the .pyc file so that the changes are not reflected in the interpreter. I would have to quit the interpreter, start it again and use import to load the module (and create the .pyc file from the .py file). Or alternatively I would have to delete the .pyc file each time.

Is there any better way? E.g., to make reload() prefer .py files over .pyc files?

Here is an except from the interpreter session that shows that reload() loads the .pyc file.

>>> reload(pdb)
<module 'pdb' from 'pdb.pyc'>

EDIT: And even if I delete the .pyc file, another .pyc file will be created each time I use reload, so that I have to delete the .pyc file each time I use reload.

>>> reload(pdb)
<module 'pdb' from 'pdb.py'>
>>> reload(pdb)
<module 'pdb' from 'pdb.pyc'>
Это было полезно?

Решение

yes. here are things you can use the -B command line option:

python -B

or use the PYTHONDONTWRITEBYTECODE environment option:

export PYTHONDONTWRITEBYTECODE=1

these make sure the .pyc files are not generated in the first place.

Другие советы

if you're using ipython, you can can do a shell command by prefixing it with !

So you could do

>>> !rm some_file.pyc
>>> reload(some_file)

Alternatively, you could define a quick function in your current shell:

>>> import os
>>> def reload(module_name):
...     os.system('rm ' + module_name + '.pyc')
...     reload(module_name)
...

and just call it whenever you want to reload your module.

You don't need to remove obsoleted *.pyc, because reload(module) does this automatically.

For this purpose I usually use something like:

    import module
    def reinit():
        try:
            reload(module)
        except:
            import traceback
            traceback.print_exc()

        call_later(1, reinit)

    reinit()
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top