vs 代码 python 键绑定被忽略

vs code python keybindings ignored

重现步骤:

  1. 将以下内容放入 keybindings.json:
// Place your key bindings in this file to override the defaults
[
    { "key": "shift+enter",           
      "command": "jupyter.execSelectionInteractive",
      "when": "editorTextFocus && jupyter.ownsSelection && !findInputFocussed && !notebookEditorFocused && !replaceInputFocussed && editorLangId == 'python'" 
    },
    {
        "key": "ctrl+shift+enter",
        "command": "python.execSelectionInTerminal",
        "when": "editorTextFocus && !findInputFocussed && !jupyter.ownsSelection && !replaceInputFocussed && editorLangId == 'python'"
    },
]
  1. 使test.py:
#%%
# move working directory to the script
import os
mydir = os.path.dirname(os.path.abspath(__file__)) 
os.chdir(mydir) 
  1. select 第 1-5 行并按下 shift+enter

预期结果(交互式 window 打开并运行脚本):

# move working directory to the script...
<director path is printed>
  1. 打印出当前目录

观察结果(在终端得到如下错误):

>>> mydir
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'mydir' is not defined

VSCode没有忽略快捷键的设置。这不是快捷键的问题,而是代码中使用的“__file__

在使用__file__时,我们需要将其作为file中的代码使用,指的是当前打开文件的路径;但是当使用命令“python.execSelectionInTerminal”时,它会进入python交互式window并将输入的内容作为独立代码执行,(如输入[=后的交互式window 27=] in the cmd window), 无法识别当前文件指的是什么。

我们可以使用其他代码来测试这个快捷方式的使用:

参考:Use of "__file__".