如何使 VSCode 自动重新加载外部 *.py 模块?

Ric*_*ard 16 python visual-studio-code

我正在 Visual Studio Code 中处理 python 代码,并使用几个函数文件,我在脚本开头导入这些文件。例如,假设我在与主脚本相同的文件夹中有一个文件“doStuff.py”,其中包含内容

def doStuff():
    print('I am doing stuff!')
    # print('lots of stuff.')
Run Code Online (Sandbox Code Playgroud)

然后我将通过编写将其导入另一个脚本,例如“main.py”

from doStuff import doStuff
doStuff()
Run Code Online (Sandbox Code Playgroud)

如果我现在运行脚本,然后例如取消注释 doStuff.py 中函数的第二行,我希望看到我的 doStuff() 方法的新行为。不幸的是,这不会发生。我最近从 Spyder 切换到 VSCode,在 Spyder 中这总是自动工作,但似乎 VSCode 不会自动重新加载导入的模块。

关于我当前工作流程的一些信息: 要打开编程环境,我使用“文件/打开文件夹”并选择 main.py 和 doStuff.py 所在的文件夹。然后我使用“在 Python 交互窗口中运行当前文件”来启动我的脚本。我猜有更好的方法,它可能与 launch.json 文件有关,但到目前为止,我发现使用更改的外部符号的唯一方法是重新启动 VSCode。

编辑: 这里的问题:Visual Studio Code: Auto-refresh file changes是不同的,如果我理解正确的话,因为它是关于要在 VS-Code 中重新加载的外部更改的文件。我的问题与在交互式窗口中重新加载 python 模块有关。

编辑2: 截图,所以你相信我。

KDL*_*Lin 14

更新:最终解决方案。只需将其添加到您的代码中即可。

%reload_ext autoreload
%autoreload 2
Run Code Online (Sandbox Code Playgroud)

========================================== 我找不到make python的方法当 .py 文件更改时,vscode 的交互会自动重新刷新。但我尝试importlib.reload(),它以某种方式起作用。

import funcs
import importlib
importlib.reload(funcs)
from funcs import *
Run Code Online (Sandbox Code Playgroud)

funcs 是我的 .py 文件,当文件更改时应该运行上面的代码。

  • `runMagicCommands` 已弃用。您可以使用: `"python.dataScience.runStartupCommands": "%load_ext autoreload\\n%autoreload 2"` (3认同)

kor*_*ral 12

我会对 leo 的回答发表评论,但我没有足够的声誉。VSCode 中 leo 的代码片段向我显示该设置未知。这对我有用:

"jupyter.runStartupCommands": [
    "%load_ext autoreload", "%autoreload 2"
],
Run Code Online (Sandbox Code Playgroud)


Leo*_*Leo 5

现在可以通过添加以下内容来自动设置自动重新加载

    "jupyter.runStartupCommands": [
        "%load_ext autoreload", "%autoreload 2"
    ]
Run Code Online (Sandbox Code Playgroud)

settings.json

  • 配置已根据此 /sf/ask/4574940961/ 进行更改“jupyter.runStartupCommands”是新的 (4认同)