273

How do I run a Python program under debug and set the working directory for the run?

user1443098
  • 6,487
  • 5
  • 38
  • 67

13 Answers13

418

@SpeedCoder5's comment deserves to be an answer.

In launch.json, specify a dynamic working directory (i.e. the directory where the currently-open Python file is located) using:

"cwd": "${fileDirname}"

This takes advantage of the "variables reference" feature in VS Code, and the predefined variable fileDirname.

Note as comments say, you might also need to add the purpose option:

"purpose": ["debug-in-terminal"]

If you're using the Python: Current File (Integrated Terminal) option when you run Python, your launch.json file might look like mine, below (more info on launch.json files here).

{
    "version": "0.2.0",
    "configurations": [
    {
            "name": "Python: Current File (Integrated Terminal)",
            "type": "python",
            "request": "launch",
            "program": "${file}",
            "console": "integratedTerminal",
            "cwd": "${fileDirname}",
            "purpose":["debug-in-terminal"]
    }, 

    //... other settings, but I modified the "Current File" setting above ...
}

Remember the launch.json file controls the run/debug settings of your Visual Studio code project; my launch.json file was auto-generated by VS Code, in the directory of my current "Open Project". I just edited the file manually to add "cwd": "${fileDirname}" as shown above.

Remember the launch.json file may be specific to your project, or specific to your directory, so confirm you're editing the correct launch.json (see comment)

If you don't have a launch.json file, try this:

To create a launch.json file, open your project folder in VS Code (File > Open Folder) and then select the Configure gear icon on the Debug view top bar.

Per @kbro's comment, you might be prompted to create a launch.json file by clicking the Debug button itself:

When I clicked on the Debug button on my navigation panel it said "To customise Run and Debug create a launch.json file." Clicking on "create..." opened a dialog asking what language I was debugging. In my case I selected Python

Nate Anderson
  • 18,334
  • 18
  • 100
  • 135
  • 15
    Any way to set this as a default setting for all configurations? – Serhiy May 17 '19 at 08:01
  • 1
    Be sure you're editing the right launch.json file! In my experience VS Code creates a .vscode directory in every project folder I open. If yesterday you opened folder parent/ and today you opened parent/child/, you'll have to make changes appropriately. – chrisinmtown Oct 26 '20 at 12:55
  • 1
    There is another file that looks similar to launch.json: workspace[x].code-workspace. It has a 'launch' key. Is this setting there similar to launch.json entries? – Timo Nov 30 '20 at 13:33
  • 1
    Can I set the folder in the terminal to the folder the script was?. E.g. my last ps1 script line is set-location foo, I want the terminal to be in foo. – Timo Nov 30 '20 at 14:33
  • 3
    This answer did not work for me, but this one did: https://stackoverflow.com/a/62331298/65326 – Apreche Dec 31 '20 at 15:50
  • What the heck is a launch.json file? Instructions make no sense. – Benbob Apr 19 '21 at 03:27
  • @Benbob, the launch.json file controls the run/debug settings of your Visual Studio code project; [more info on the launch.json file here](https://code.visualstudio.com/docs/editor/debugging#_launch-versus-attach-configurations) – Nate Anderson Apr 19 '21 at 21:05
  • 1
    This current code can be fixed with this. https://github.com/microsoft/vscode-python/issues/18299 – sickerin Feb 13 '22 at 13:47
  • @Serhiy not that I'm aware of, but you can make just make a template `launch.json` locally and copy that information in each time you're creating a new launch.json – jryan14ify Oct 18 '22 at 14:24
  • 1
    Make sure to debug by hitting F5 or from the left debug pane "Run and Debug" -> Start Debugging. The Debug button on the upper right did not work. – Haider Nov 29 '22 at 21:59
  • 1
    When I clicked on the Debug button on my navigation panel it said "To customise Run and Debug _create a launch.json file_." Clicking on "create..." opened a dialog asking what language I was debugging. In my case I selected Python. – kbro Jan 09 '23 at 16:46
  • 3
    TLDR; to run debugger from cwd, add `"purpose":["debug-in-terminal"]` in launch.json – haneulkim Jan 11 '23 at 05:36
  • Thanks @haneulkim , I wasn't aware of the `"purpose"` attribute in the launch.json file, this [link describes it in more detail](https://code.visualstudio.com/docs/python/debugging#_purpose) I don't know why the `"purpose"` attribute is not mentioned in the [`launch.json` attributes documentation](https://code.visualstudio.com/docs/editor/debugging#_launchjson-attributes). I would edit my answer to mentioned `"purpose"`, but I haven't tested it and I worry about comments like "Note: The purpose option can't be used to start the debugger through F5 or Run > Start Debugging" – Nate Anderson Jan 11 '23 at 18:38
  • 1
    Setting `cwd` alone didn't work for me, adding purpose did the trick. VSCode 1.80.1 on linux. – Roman Luštrik Jul 26 '23 at 17:58
  • Thanks @RomanLuštrik , you said that and haneulkim said that, so I added `"purpose": ["debug-in-terminal"]` to the answer – Nate Anderson Jul 27 '23 at 17:56
65

Configure the cwd setting in launch.json as follows:

{
    "name": "Python",
    "type": "python",
    "pythonPath": "python", 
    ...
    "cwd": "<Path to the directory>"
    ...
}
Mateen Ulhaq
  • 24,552
  • 19
  • 101
  • 135
Don
  • 6,632
  • 3
  • 26
  • 34
37

This setting helps me: (I am a Windows person)

{
  "type": "node",
  "request": "launch",
  "name": "Launch Program",
  "cwd": "${workspaceFolder}\\app\\js", // set directory here
  "program": "${workspaceFolder}\\app\\js\\server.js", // set start js here
}
Xin
  • 33,823
  • 14
  • 84
  • 85
36

In some cases, it might be also useful to set the PYTHONPATH along with the workspaceFolder:

{
    "name": "Python: Current File",
    "type": "python",
    "request": "launch",
    "program": "${file}",
    "console": "integratedTerminal",
    "cwd": "${workspaceFolder}",
    "env": {
        "PYTHONPATH": "${cwd}"
    }
}

CermakM
  • 1,642
  • 1
  • 16
  • 15
  • 4
    thanks, that helped. but I am not sure I understand why is that needed. Can you explain it please? – Hanan Shteingart Jan 26 '21 at 20:48
  • 1
    @HananShteingart, see Python documentation: https://docs.python.org/3/using/cmdline.html?highlight=pythonpath#envvar-PYTHONPATH – ahogen Mar 05 '23 at 22:22
  • "In some cases" – which cases? – Ooker May 27 '23 at 16:22
  • @Ooker in the caes where you have a module but you don't know what is happening in your vscode, this happened to me today, I was prepping an environment for fresh-techies where I needed to set up a module with __main__.py in the root and __init__.py in almost every sub-directory, at least this was my case. So we needed to run the file, but keep the env for the root as the project root directory – mr.xed Jun 06 '23 at 17:24
6

I am posting this sample configuration for people who use TypeScript on Node.js

in my project my Node.js server TypeScript files are located in folder Application_ts and the compiled js files are generated in the folder named Application

because when we run our application in debug mode or start it normally we should start from Application folder which contains the js files so bellow configuration run debug from root folder where my application_ts also exists and works perfect

{
  "version": "0.2.0",
  "configurations": [
    {
        "type": "node",
        "request": "launch",
        "name": "Debug TypeScript in Node.js",
        "program": "${workspaceRoot}\\Application\\app.js",
        "cwd": "${workspaceRoot}\\Application",
        "protocol": "inspector",
        "outFiles": [],
        "sourceMaps": true
    },        
    {
        "type": "node",
        "request": "attach",
        "name": "Attach to Process",
        "port": 5858,
        "outFiles": [],
        "sourceMaps": true
    }
 ]
}
MJ X
  • 8,506
  • 12
  • 74
  • 99
4

In order to make this work globally I had to do the following. Updating only the launch.json file only solves it in the folder where VSCode currently is open.

  1. Locate the settings.json file.

    Windows %APPDATA%\Code\User\settings.json

    macOS $HOME/Library/Application\ Support/Code/User/settings.json

    Linux $HOME/.config/Code/User/settings.json

  2. Update the file.

{
    // -- other default or custom settings from before

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

More information here and here.

Jakob
  • 663
  • 7
  • 25
  • 1
    This worked. The additional line of "purpose": ["debug-in-terminal"] was the difference maker for me from the top answer. – mkohler Apr 26 '23 at 21:40
3

You can set up current working directory for debugged program using cwd argument in launch.json

Krzysztof Cieslak
  • 1,695
  • 13
  • 14
2

To set current working directory to whatever file you are executing at the time:

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

Thanks brch: Python in VSCode: Set working directory to python file's path everytime

Jake
  • 101
  • 1
  • 5
1

It is important to set PYTHONPATH, you can set it on vscode:

{
    "name": "Python debug",
    "type": "python",
    "request": "launch",
    "program": "${file}",
    "console": "integratedTerminal",
    "cwd": "${workspaceFolder}",
    "env": {
        "PYTHONPATH": "${cwd}"
    }
}

Or just set it on terminal with:

$export PYTHONPATH=/home/user/myproject:$PYTHONPATH

Here /home/user/myproject is your project path.

moken
  • 3,227
  • 8
  • 13
  • 23
Just
  • 11
  • 1
0

I faced the same issue and noticed that when running the which python command in Terminal in Mac it shows me a different path to what I get when I run the which python command in vs code. And also that my file runs properly in the terminal when run using python filename.py

So I copied that path from the terminal and pasted it in VS code into Preferences->Settings->Extensions->Python->Default Interpreter Path and it worked. I hope this helps.

0

I use the "justMyCode = false" so I can also debug and jump into the functions that the main script calls.

{
    // 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",
            "justMyCode": false,
            "cwd": "${fileDirname}"        }
    ]
}
0

Setting "cwd" to ${FileDirname} in launch.json did not work for me. I tried modifying settings.json, and this worked for me.

In the settings.json file, add this field: "python.terminal.executeInFileDir": true

After adding this field, my settings.json looks something like:

{
    "python.terminal.executeInFileDir": true
}

This will definitely set the cwd to the directory that contains your file, and not the root folder that the project is hosted in.
Aabesh Ghosh
  • 101
  • 2
-1

In my case, I kill debug terminal and re-run.

Yunus Emre
  • 29
  • 1
  • 6
  • This answer does not completely address the question. Please [edit](https://stackoverflow.com/posts/76093164/edit) and update your answer with further details. – moken May 01 '23 at 02:03