想象一下,运行一个python脚本需要很长时间,如果我在运行时修改它会发生什么?结果会不同吗?
当前回答
什么都没有发生。一旦脚本加载到内存中并运行,它将保持如下所示。
“自动重新加载”特性可以在代码中实现,就像Flask和其他框架一样。
其他回答
没有,因为Python将脚本预编译为PYC文件并启动该文件。
但是,如果发生了某种异常,您可能会得到一个略微具有误导性的解释,因为行X的代码可能与启动脚本之前的代码不同。
执行以下脚本:
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”。
没有,就像这个答案。此外,我还做了涉及到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
这与你在问题中描述的略有不同,但它是有效的:
my_string = "Hello World!"
line = input(">>> ")
exec(line)
print(my_string)
测试运行:
>>> print("Hey")
Hey
Hello World!
>>> my_string = "Goodbye, World"
Goodbye, World
您可以动态地更改“加载”代码的行为。
当你运行一个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__顶级代码环境
推荐文章
- 证书验证失败:无法获得本地颁发者证书
- 当使用pip3安装包时,“Python中的ssl模块不可用”
- 无法切换Python与pyenv
- Python if not == vs if !=
- 如何从scikit-learn决策树中提取决策规则?
- 为什么在Mac OS X v10.9 (Mavericks)的终端中apt-get功能不起作用?
- 将旋转的xtick标签与各自的xtick对齐
- 为什么元组可以包含可变项?
- 如何合并字典的字典?
- 如何创建类属性?
- 不区分大小写的“in”
- 在Python中获取迭代器中的元素个数
- 解析日期字符串并更改格式
- 使用try和。Python中的if
- 如何在Python中获得所有直接子目录