Wrong current working directory when running python code and jupyter extension in vscode

Question:

I am trying to run python code using the jupyter extension in vscode here

I have a workspace open at this location
/Users/user/Documents/
When I try and run the following code in a file called test.py in a child directory, the current working directory is set at the workspace level rather than the file. Is it possible to change a setting to use the cwd of the file, rather than the workspace? I cannot find one in settings.json and the “cwd” in launch.json only seems applicable to debugging.

File location:
/Users/user/Documents/python_code/test.py

#%%
import os
print(os.getcwd())

Expected output:
/Users/user/Documents/python_code/

Actual output:
/Users/user/Documents/

When running the same code through the terminal it prints the expected result, so the issue seems to be related to the jupyter extension

Asked By: arabella

||

Answers:

There is the setting python.dataScience.notebookFileRoot which is, as far as I understand, supposed to achieve the expected behaviour when setting it to ${fileDirname}.
See correspoding source.

However, it does not seem to work in my case. Maybe a bug?

Note that the output of running the script from the terminal depends on you working directory of the terminal!

Answered By: fkjogu

For any specific folder / workspace that you have open in VS Code you can use the notebookFileRoot setting to set a specific absolute path directory to always set the Jupyter working directory to when you start the Interactive Window with that folder open.

Always opening on the file location (without having to set notebookFileRoot to an absolute path per folder) is not supported via the notebookFileRoot setting. The VSCode variables such as ${fileDirname} are specific to task and debug configuration files (launch.json and task.json). We’ve specifically added code to recognize ${workspaceFolder} for our settings page but we don’t recognize other VSCode variables in there.

If you want there is a github item here that has suggested this feature. You can follow that or vote it up if you want this feature added.
https://github.com/Microsoft/vscode-python/issues/4441

Edit 11/5/2019:
We have now made a change to allow the VS Code “Notebook File Root” setting to be set to ${fileDirname}. This setting will now start up Notebook Editor and Interactive Window session relative to the file location that was used to start them.

Answered By: Ian Huff

For those using remote jupyter server – you can use this answer I gave here: https://stackoverflow.com/a/75873316/4394355

But it boils down to add this to your user json settings file:

{
"jupyter.runStartupCommands": [
        "import os",
        "__t=os.path.dirname(__vsc_ipynb_file__)",
        "%cd {__t}",
        "del __t"
    ],
}

Please note that it’s using undocumented variable.

Answered By: THOTH