简体   繁体   English

如何在 VSCode 中重新启动内核以完全重新加载导入?

[英]How to restart kernel in VSCode to completely reload imports?

When I change an imported python script when running cell by cell imports doesn't work until I restart the whole program VSCode.当我在逐个单元格导入时更改导入的 python 脚本时,在我重新启动整个程序 VSCode 之前不起作用。 I tried to kill kernel and restart it, saved changes - nothing works, only restarting is need.我试图杀死内核并重新启动它,保存更改 - 没有任何效果,只需要重新启动。 But it isn't too quick and appropriate to restart it each time I change the code.但是每次更改代码时重新启动它并不太快也不太合适。 Is there any way to apply changes in imported scripts?有没有办法在导入的脚本中应用更改? I am on linux lubuntu 20.04.我在 linux lubuntu 20.04 上。

This works for me:这对我有用:

%load_ext autoreload
%autoreload 2

Execute those lines after your imports and any saved changes you make to the external file you are importing should get automatically reflected.在导入后执行这些行,并且您对导入的外部文件所做的任何已保存更改都应自动反映。

When I change an imported python script when running cell by cell imports doesn't work until I restart the whole program VSCode.当我在逐个单元格导入时更改导入的 python 脚本时,在我重新启动整个程序 VSCode 之前不起作用。

If you are trying to change and save an imported python file, running cell by cell does not work like that.如果您尝试更改和保存导入的 Python 文件,则无法按单元运行。 You will have to save all the changes in first go, and then try executing cell by cell;您必须先保存所有更改,然后尝试逐个单元执行; that is because in cell by cell execution in VSCode is handled by a stack and no exclusive information like unchanged data/status is available to that stack.这是因为在 VSCode 中逐个单元地执行由堆栈处理,并且该堆栈没有可用的独占信息,例如未更改的数据/状态。 That's why you'll have to first make all the changes, and then execute.这就是为什么您必须首先进行所有更改,然后再执行。

A good solution to this problem is using importlib :这个问题的一个很好的解决方案是使用importlib

import my_changed_module as mc
import importlib

importlib.reload(mc)

This will reload your module everytime you run your script.这将在您每次运行脚本时重新加载您的模块。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM