想象一下,运行一个python脚本需要很长时间,如果我在运行时修改它会发生什么?结果会不同吗?


当前回答

没有,就像这个答案。此外,我还做了涉及到multiprocessing的实验。将下面的脚本保存为x.py:

import multiprocessing
import time

def f(x):
    print(x)
    time.sleep(10)

if __name__ == '__main__':
    with multiprocessing.Pool(2) as pool:
        for _ in pool.imap(f, ['hello'] * 5):
            pass

在python3 x.py和前两个'hello'被打印出来之后,我将['hello']修改为['world']并观察发生了什么。没有什么有趣的事情发生。结果仍然是:

hello
hello
hello
hello
hello

其他回答

当你运行一个python程序并启动解释器时,发生的第一件事是:

初始化模块sys和builtins __main__模块被初始化,这是你作为参数提供给解释器的文件;这将导致代码执行

When a module is initialized, it's code is run, defining classes, variables, and functions in the process. The first step of your module (i.e. main file) will probably be to import other modules, which will again be initialized in just the same way; their resulting namespaces are then made available for your module to use. The result of an importing process is in part a module (python-) object in memory. This object does have fields that point to the .py and .pyc content, but these are not evaluated anymore: module objects are cached and their source never run twice. Hence, modifying the module afterwards on disk has no effect on the execution. It can have an effect when the source is read for introspective purposes, such as when exceptions are thrown, or via the module inspect.

这就是为什么在添加不打算在导入模块时运行的代码时,检查__name__ == "__main__"是必要的。以main方式运行该文件等同于导入该文件,除了__name__有不同的值。


来源:

导入模块时会发生什么:导入系统 解释器启动时会发生什么:顶级组件 什么是__main__模块:__main__顶级代码环境

没有,因为Python将脚本预编译为PYC文件并启动该文件。

但是,如果发生了某种异常,您可能会得到一个略微具有误导性的解释,因为行X的代码可能与启动脚本之前的代码不同。

不同。如果一个python脚本链接到其他修改过的文件,那么当然会加载更新的版本。但是如果源不指向任何其他文件,它就会运行缓存中的所有脚本,只要它运行。下次就能看到变化了…

如果关于自动应用更改,是的,@pcbacterio是正确的。它可以做thar,但脚本,它只记得最后的动作/事情是做什么,并检查当文件被修改重新运行它(所以它几乎不可见)

=]

这与你在问题中描述的略有不同,但它是有效的:

my_string = "Hello World!"

line = input(">>> ")
exec(line)

print(my_string)

测试运行:

>>> print("Hey")
Hey
Hello World!

>>> my_string = "Goodbye, World"
Goodbye, World

您可以动态地更改“加载”代码的行为。

执行以下脚本:

from time import sleep

print("Printing hello world in: ")
for i in range(10, 0, -1):
    print(f"{i}...")
    sleep(1)
    
print("Hello World!")

然后将“Hello World!”更改为“Hello StackOverflow!”当它开始倒数时,它仍然会输出“Hello World”。