Python in VSCode: Set working directory to python file's path everytime
Asked Answered
O

9

28

So I want to migrate from Spyder to VSCode, and I come across this problem where I cannot access a dataset as my working directory is not the same as the dataset's path.

launch.json is not auto-generated for me as I'm not debugging anything (I tried this).

How do I set the working directory to always be the dir of the Python file I want to run, in VSCode? (and if it's bad practice, could you show me a config that is easy to work with?) I'd like to set this up for VSCode's IPython terminal.

Odel answered 26/6, 2019 at 15:40 Comment(2)
That configuration you linked should achieve that, have you tried it? did it work?Tamratamsky
@Tamratamsky I don't know how to set it up. Is it under .vscode folder in root directory?Odel
C
21

Updated Solution: working as of 21/1/2021

Option 1:

  1. Locate and open the user settings file:
    • Windows %APPDATA%\Code\User\settings.json
    • macOS $HOME/Library/Application Support/Code/User/settings.json
    • Linux $HOME/.config/Code/User/settings.json
  2. Add this line: "python.terminal.executeInFileDir": true

Option 2:

  1. Open the Settings editor:
    • On Windows/Linux - File > Preferences > Settings
    • On macOS - Code > Preferences > Settings
    • or use the keyboard shortcut (Ctrl+,).
  2. Check the following box:
    • Extensions > Python > Terminal: Execute In File Dir.
    • or use the Search bar and type this setting id python.terminal.executeInFileDir.
Cocainism answered 21/1, 2021 at 20:14 Comment(2)
Sounds good in theory but it doesn't work. Shift+Enter still launches python in my home dir instead of the script dir.Knowland
As of august 2022, none of these work.Michamichael
W
26

Modify this setting:

File > Preferences > Settings > Python > Data Science > Execute in File Dir

Wicketkeeper answered 11/6, 2020 at 18:40 Comment(4)
"cwd": "${fileDirname}" in launch.json did not work for me. But this did. Now current working directory is set to the file location. Thank you!Henninger
Is there a way to do this for Debug as well?Ceja
There's no "Python" under Settings here.Michamichael
@ShepBryan this helped me to set it for debug as well: github.com/microsoft/vscode-python/issues/…Reconcilable
C
21

Updated Solution: working as of 21/1/2021

Option 1:

  1. Locate and open the user settings file:
    • Windows %APPDATA%\Code\User\settings.json
    • macOS $HOME/Library/Application Support/Code/User/settings.json
    • Linux $HOME/.config/Code/User/settings.json
  2. Add this line: "python.terminal.executeInFileDir": true

Option 2:

  1. Open the Settings editor:
    • On Windows/Linux - File > Preferences > Settings
    • On macOS - Code > Preferences > Settings
    • or use the keyboard shortcut (Ctrl+,).
  2. Check the following box:
    • Extensions > Python > Terminal: Execute In File Dir.
    • or use the Search bar and type this setting id python.terminal.executeInFileDir.
Cocainism answered 21/1, 2021 at 20:14 Comment(2)
Sounds good in theory but it doesn't work. Shift+Enter still launches python in my home dir instead of the script dir.Knowland
As of august 2022, none of these work.Michamichael
T
10

You can find more details on the launch.json setting file in the Visual Studio Code User Guide, included how to create one and what it means.

In short, you should be able to just create a launch.json file in a .vscode subfolder of the directory you usually open with Open Worspace and paste the snippet provided by the other answer. If you find that it doesn't work, you can try changing the cwd option going from this:

            "cwd": "${fileDirname}"

to this

            "cwd": ""
Tamratamsky answered 26/6, 2019 at 15:45 Comment(4)
…actually, also required me to manually cd into $fileDirname before running the script with "console": "integratedTerminal"Grimaldi
The wording of this answer is confusing. "... just create a launch.json file a .vscode subfolder ..." Is it one, the other, or both?Michamichael
@EzequielBarbosa missing a preposition. you should have .vscode/launch.json at the end, create whatever is missing :)Tamratamsky
This works but you have to do this for every new project you start on. Isn't there a way to make this setting global? I've tried adding these settings in ~/.vscode/launch.json instead but no luck.Freer
A
8

Updated Solution working as of 24th of January 2022

It can be changed in the Settings menu. Go to File > Preferences > Settings and Search for "Execute in File Path". You will find a option which is called:

Python > Terminal: Execute In File Dir
  When executing a file in the terminal, whether to use execute in the file's directory, instead of the current open folder.
Ashleyashli answered 24/1, 2022 at 9:42 Comment(2)
Apparently you have to open the dir as a workspace in code, not just a script file github.com/microsoft/vscode-python/issues/… Who does that? Total rubbish.Knowland
For me it was working, I'm sorry if It didn't work for you.Ashleyashli
S
7

This worked for me:

include this in your /.vscode/launch.json

{
    "name": "Python: Current File",
    "type": "python",
    "request": "launch",
    "program": "${file}",
    "console": "integratedTerminal",
    "justMyCode": false,
    "cwd": "${fileDirname}",
    "purpose": ["debug-in-terminal"]
}

Source.

Selda answered 30/1, 2023 at 12:52 Comment(1)
the "purpose": ["debug-in-terminal"] was the thing that made it work as I was going down this page trying everything!Nickname
K
5

Mind you the solutions on this page don't work unless you open the dir as a workspace in Code. If you just open the script, none of these answers work.

MSFT doesn't see this as an issue worth fixing. Because everyone on their island works in workspaces not with scripts, even with scripting languages.

Knowland answered 11/2, 2022 at 12:45 Comment(0)
S
3

I tried all these solutions to no effect. My problem was just to access files from the current folder in python, I solved doing in the beginning of the script:

os.chdir(os.path.dirname(__file__))

Semitone answered 26/1, 2023 at 23:21 Comment(0)
P
1

What worked for me (16/01/2023) is going to File > Preferences > Settings and I just started typing "execute file in" in the 'Search settings' field and the top result was "Python › Terminal: Execute In File Dir". Can't comment on the debug environment. Note: Settings can be accessed by using shortcut "Ctrl+,".

Pradeep answered 16/1, 2023 at 15:9 Comment(5)
As of [28/02/2023] there is no preferences under file.Galengalena
Yes, there is today (01/03/2023) on VSCode 1.75.1. For the sake of usability, I have added the default shortcut to "Settings". Official docs from 2/2/23: code.visualstudio.com/docs/getstarted/settings Not sure why you are missing yours.Pradeep
How utterly bizarre. I genuinely don't have that option under File. I am on a Mac and on the same version 1.75.1. That is very odd.Galengalena
You have it under Code on Mac @Astrid. The rest of the steps are the same.Freer
Apologies for assuming Windows. Anyway, as an update: code.visualstudio.com/docs/getstarted/settings from 3/1/2023 on VScode 1.76.0. But also, if you had opened the link (and potentially scrolled down once, depending on the size and resolution of your screen) you would have seen the set of instructions for "On Windows/Linux" and "On macOS". Obviously, I'm not capable of explaining why it's different for Win/Lin and Mac. Out of curiosity, does the shortcut Ctrl+, (comma) work for you? Macs don't have Ctrl though, do they; it's Cmd perhaps?Pradeep
C
0

Add the following settings to your settings.json

    "python.terminal.executeInFileDir": true,
    "code-runner.fileDirectoryAsCwd": true

To Dr. S's solution I added the "code-runner.fileDirectoryAsCwd": true setting from the Code Runner extension. The first setting sets the working directory to the python file path only if it is run in the terminal. However, the working directory will revert to the root directory if the code is run in the Output tab with CTRL+ALT+N. This may also be the reason why any settings in the launch.json file such as "cwd": "${fileDirname}" do not work, as I have tried as well. The second setting solves this, which allows you to set the working directory to the python file's path even when you choose to run code outside of the terminal.

Casaubon answered 19/5, 2021 at 13:22 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.