3

I am using a pretty common project structure with python packages at the top level of the containing directory and subdirectories named scripts and tests. Generally what you want with this setup is for the top level folder to be added to sys.path so that you can just say import mypackage in your scripts and tests.

I found that I had to use two different mechanisms, - adding a .env file to set PYTHONPATH for the tests and linting etc. and setting the terminal.integrated.env.windows for the terminal.

However neither of these seem to affect the Python Interactive window, so if I define a cell using #%% in a script (not a notebook) and run it with Ctrl-Enter, then it wont be able to find my packages located at the root of the project dir.

Is there a way to achieve what I want without changing my source files? Ideally there would be one way of setting the import path that works everywhere without having to specify an absolute path as in the case of the .env file. Spyder for example can do this with its PYTHONPATH manager and adds the root directory of projects by default.

Shane
  • 2,271
  • 3
  • 27
  • 55
  • I have tried it locally, everything goes well. Both Jupyter Notebook and Python Interactive can find the values of 'PYTHONPATH' property in the 'sys.path' which was defined in .env file. After you configure the .env file, you'd better restart the VSCode or Jupyter Server. – Steven-MSFT Sep 02 '20 at 03:16

1 Answers1

2

The magic keyword in the settings you are looking for is jupyter.notebookFileRoot. So in your settings.json add something like

"jupyter.notebookFileRoot": "${workspaceFolder}"

or whatever folder you need.

Alternatively, go to Settings (CTRL + ,), select the Workspace tab and scroll down to or search for Jupyter: Notebook File Root and enter your folder there.

In the settings file you can also add launch-configurations etc. My settings file currently looks like this and supports running a complete Python file (CTRL + F5) as well as interactive mode (run cells defined by # %%):

{
    "launch": {
        "version": "0.2.0",
        "configurations": [
            {
                "name": "Python: Current File",
                "type": "python",
                "request": "launch",
                "program": "${file}",
                "console": "integratedTerminal",
                "env": {
                    "PYTHONPATH": "${workspaceFolder}"
                },
                "cwd": "${workspaceFolder}"
            }
        ]
    },
    "jupyter.notebookFileRoot": "${workspaceFolder}"
}
spettekaka
  • 411
  • 3
  • 11