6

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'>
4

3 回答 3

3

是的。以下是您可以使用命令行选项-B内容:

python -B

或使用PYTHONDONTWRITEBYTECODE环境选项

export PYTHONDONTWRITEBYTECODE=1

这些确保.pyc文件不是首先生成的。

于 2013-07-15T20:56:30.400 回答
0

如果您使用的是 ipython,则可以通过添加前缀来执行 shell 命令!

所以你可以做

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

或者,您可以在当前 shell 中定义一个快速函数:

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

并且只要你想重新加载你的模块就调用它。

于 2013-07-15T20:57:01.527 回答
0

您不需要删除过时的 *.pyc,因为 reload(module) 会自动执行此操作。

为此,我通常使用类似的东西:

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

        call_later(1, reinit)

    reinit()
于 2014-12-13T17:42:15.373 回答