1

I found this answer very useful to understand relative imports in Python. However I have found difficulty in getting VS Code's "Current File" to play nicely with this, since it launches the file directly using ${file}.

To summarise said answer, suppose we have a structure like this:

mymod/
    __init__.py
    apple.py
    orange.py

If orange.py imports something from apple.py:

from .apple import apple_function

then the correct way to run orange.py as a script without an ImportError is with the following command from the directory containing mymod:

python -m mymod.orange

Currently, I manually enter a command similar to the above into the terminal, which works, but I'd prefer to use a keyboard shortcut that works regardless of filename and saves me some typing.

Is there anything I can add to the launch.json to have a configuration that launches python for each particular file as above automatically?

  • 1
    change the `cwd` property of the launch config to be the directory of the file `${workspaceFolder}/${relativeFileDir}` (search for the correct name of the variables) – rioV8 Apr 25 '21 at 19:45
  • This put me on the right track, and I've got something that almost works. By setting `cwd` to `${workspaceFolder}` and swapping out `"program":"${file}"` for `"module":"${relativeFileDirname}${pathSeparator}${fileBasenameNoExtension}"`, it launches with `python [debugpy] -m path/to/module`. This is almost correct, all that would need to be done is to swap out path separators for full stops. Either way, this clearly isn't supported by VS Code, so unless there's an intended way I should be asking them to add this as a feature rather than adding this hack. – itdobelikethat Apr 26 '21 at 08:38

1 Answers1

1

Use the command extension.commandvariable.file.relativeDirDots from the extension Command Variable

{
  "version": "0.2.0",
  "configurations": [
    {
      "name": "Python: Module",
      "type": "python",
      "request": "launch",
      "console": "integratedTerminal",
      "module": "${command:extension.commandvariable.file.relativeDirDots}.${fileBasenameNoExtension}",
    }
  ]
}
rioV8
  • 24,506
  • 3
  • 32
  • 49