简体   繁体   中英

vs code python keybindings ignored

Steps to reproduce:

  1. Put the following in 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. make test.py:
#%%
# move working directory to the script
import os
mydir = os.path.dirname(os.path.abspath(__file__)) 
os.chdir(mydir) 
  1. select lines 1-5 and hit shift+enter

Expected result (an interactive window opens and runs the script):

# move working directory to the script...
<director path is printed>
  1. prints out the current directory

Observed result (get the following error in the terminal):

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

VSCode did not ignore the setting of shortcut keys. This is not a problem caused by the shortcut key, but the " __file__ " used in the code.

When using __file__ , we need to use it as code in the file , referring to the path of the currently opened file; but when using the command " python.execSelectionInTerminal ", it will enter the python interactive window and execute the entered content as independent code, (like The interactive window after typing python in the cmd window), it cannot identify what the current file refers to.

We can use other code to test the use of this shortcut:

在此处输入图片说明

Reference: Use of " __file__ " .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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