48

When executing "Run Selection/Line in Python Terminal" command in VSCode, terminal's current working directory is the workspace root directory. How can we set current directory of terminal to the current file's directory when running the selection/line?

1

9 Answers 9

41

In "User Settings", use the search bar to look for "python.terminal.executeInFileDir" and set (=) its value to "true" instead of "false".

Sign up to request clarification or add additional context in comments.

4 Comments

I dont think this seems to work. interactive window is related to the notebook file root settings
this doesn't answer the original question but it was the answer I was looking for so have an upvote +1
I don't see 'User settings' in current VS Code This worked for me on one computer but on a different station 11-2021. I went to general settings, typed python.terminal.executeInFileDir and set the chechkmark for both User and Workspace. But, when I try to run the a file os.getcwd() gives me the Open Folder location, which is one directory up, not the file's location. Any idea?
This works for "Run Python File" in VS Code 1.84.2 (but not for the problem in the question). Thank you anyway :)
17

I used the option Run -> Add Configuration (or Open configuration, if available) This will open your current 'launch.json' file. Now you may add this line to the configuration wanted (in my case was Python):

"cwd": "${fileDirname}"

This line will make VSCode to run your stuff in the same folder as the file is being executed.

You can get more details in this link: https://code.visualstudio.com/docs/editor/variables-reference

Here is my full json file (just for reference):

{
    // Use IntelliSense to learn about possible attributes.
    // Hover to view descriptions of existing attributes.
    // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
    "version": "0.2.0",
    "configurations": [                
                    
        {
            "name": "Python: Current File",
            "type": "python",
            "request": "launch",
            "program": "${file}",
            "console": "integratedTerminal",
            "cwd": "${fileDirname}"            
            
        }
    ]
}

1 Comment

This works for "Run and Debug: Python: Current File", but not for the problem in the question. Thank you anyway :)
14

Update following release 2019.10.44104

Following release 2019.10.44104 of the VS Code python extension, you can now set the python.dataScience.notebookFileRoot to ${fileDirname} to directly start the python interactive window in the directory of the file you're running.

Note that the root directory will not change if you then run code from another file unless you interrupt/restart the kernel (or close VS Code). On this aspect, see the following comment and the corresponding github issue.


For the Python Interactive Window, the setting you're looking for is python.dataScience.notebookFileRoot. However, as explained in this answer to a similar question,

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).

See also the associated github issue.

As indicated, you can still set this setting to a specific absolute path, which might be enough if you're mainly working on a single project at a time.

Alternatively, you could also add the following code at the top of your script/notebook:

import os
os.chdir('absolute-path-to-workingDir')

2 Comments

As of 2022, I don't think option is available anymore (running VSCode 1.73.1).
@RaulGuariniRiva there is a "jupyter.notebookFileRoot": "${fileDirname}", now. However, it did not solve the problem eather in my case...
1

you need to go to file/preferences/user settings and click the "{}" icon at the top right of the window. After that, put this setting in: "terminal.integrated.cwd": "C:\\Users\\myUser\\", and after that wherever your terminal's directory happens to be. This answer is not the most inaccurate cause im still a noob myself at using vscode so if someone more experienced with it could reply to this thread it would be great.

Comments

1

There is no straightforward way to achieve this yet. In search for a better solution, I have a workaround with the Terminal Here extension in the VScode Marketplace. This extension allows you to open an integrated terminal in the current file's directory. This extension combined with a few more steps and you should get the desired behavior.

  • Once the extension is installed, make sure your file window is in focus, and press ctrl+shift+p and execute Terminal Here: Create Terminal. This will create a new terminal in the file's directory.
  • Type python in the terminal to launch the Python interpreter.
  • Now, position the cursor on the line you wish to execute and press ctrl+shift+p and execute Terminal: Run selected text in active terminal. This will run that line of code in the open python interpreter.

The first two steps are required only for the first time you run a code selection in the Python interpreter in the current file's directory. All subsequent selections can be run with the third step. To make things quicker, you could attach custom keybindings to the first and last steps.

Comments

0

This options will help you. File->Preferences->Settings. Add or edit the below setting.

terminal.integrated.shell.windows": ""

From the next terminal it will be reflected.

And add .profile to your default shell and add default path to it.

More information at: https://code.visualstudio.com/docs/editor/integrated-terminal

Comments

0

you may also do the opposite (i.e. change the running directory of the interactive window). This is done by following the instructions below:

Open VSCODE settings (Ctrl + ,), type "python.dataScience.notebookFileRoot". There, under Jupyter: Notebook File root change "${fileDirname}" to "${workspaceFolder}".

Comments

0

Open vscode settings.json, add:

"jupyter.runStartupCommands": [
    "import sys",
    "sys.path.append('/home/whatever_path_you_want')",
],

1 Comment

Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.
-1

this issue is answered here. The solution is to config the launch.json file in .vscode folder

2 Comments

While this link may answer the question, it is better to include the essential parts of the answer here and provide the link for reference. Link-only answers can become invalid if the linked page changes. - From Review
The referred tutorial addresses a different problem: debugging a Python file.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.