python模块何时重新编译?

2024-10-04 03:18:19 发布

您现在位置:Python中文网/ 问答频道 /正文

如果主python程序首先初始化一组模块,然后等待运行它们的defRun()函数,那么如果发生更改,它将在何时重新编译模块

考虑下面的例子…

主脚本

import mod_a
import mod_b
import mod_c

a = mod_a(<arg>)
b = mod_b(<arg>)
c = mod_c(<arg>)

list_to_run = [a, b, c]

for module in list_to_run:
    module.Run()

假设mod_a.Run()和mod_b.Run()需要一些时间来运行

我开始主脚本

mod_a.Run()运行时,我在mod_c.Run()中进行更改并删除mod_c.pyc文件

当主脚本调用mod_c.Run()时,它会重新编译并合并更改吗


Tags: 模块to函数runimport程序脚本mod
1条回答
网友
1楼 · 发布于 2024-10-04 03:18:19

编译在导入时进行。一旦你导入它,你甚至可以删除源文件,它仍然可以工作

(2) % ls
foo.py
(2) % cat foo.py
def display():
    print ("Hello, world")
(2) % python
Python 3.5.2 |Anaconda 4.2.0 (64-bit)| (default, Jul  2 2016, 17:53:06)
[GCC 4.4.7 20120313 (Red Hat 4.4.7-1)] on linux
Type "help", "copyright", "credits" or "license" for more information.
[3.5.2] >>> import foo # Imports foo
[3.5.2] >>> # Now the file is also compiled and stored in __pycache__
[3.5.2] ...
[3.5.2] >>> import shutil
[3.5.2] >>> shutil.rmtree("__pycache__")
[3.5.2] >>> import os
[3.5.2] >>> os.unlink("foo.py")
[3.5.2] >>> # Hit Ctrl-Z here to suspend the interpreter
zsh: suspended  python
-148-(3) % ls # No files here. Everything is deleted
(3) % fg
[3]  - continued  python


[3.5.2] >>> foo.display()
Hello, world
[3.5.2] >>> # Still works.

相关问题 更多 >