How to debug files in subfolders in Visual Studio Code#

A common way to organize cluster jobs is to put them all in separate files that sit in a dedicated folder a.k.a. python package.

A nice way to develop and to debug them is to be able to run those files as scripts by adding the if __name__ == '__main__': clause at the end and calling your job from there.

Debugging them in Pycharm is quite easy, but doing this in VS Code needs some setting up if you happen to import something from a package that is not within the package of the job.

Let’s assume, we have a simple job like this:

from obob_condor import Job
from my_functions.hello_sayer import say_hello

class MyJob(Job):

    def run(self, text):
        say_hello(text)

if __name__ == '__main__':
    job = MyJob('Hello World')

    job.run_private()

And the folder structure is something like this:

jobs
  |--> my_job.py
my_functions
  |--> hello_sayer.py

Running the above job on the cluster is going to work because it is run from the main folder.

If you run or debug it in VS Code, the script is going to run from within the jobs folder, so it cannot access the my_functions package.

There are two things that you need to do to make this work:

Tweak some settings#

In VS Code open the Settings. Either by using the menu or by typing Ctrl + ,.

Note

As with almost all settings in VS Code you can use the tabs right below the search field to determine where these settings apply:

  • User: Apply to all workspaces

  • Remote: Only apply to the current remote connection (Only available if one is open)

  • Workspace: Only apply to the current workspace

Search for the setting called Jupyter: Notebook File Root and change it to: ${workspaceFolder}.

The default configuration enables debug functionality only in your own code. Most of the time, this is what you want. However, if you need to dig into MNE Python code or code of another package, you can change disable Jupyter: Debug Just My Code.

Do not use the normal Run/Debug button#

These settings do not take effect there.

Instead, open the command palette and choose Jupyter: Debug Current File in Interactive Window.