Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to launch python in Visual Studio Code with superuser permission or root permission? (i.e. using sudo command)

To execute my python program from the command line, I use sudo python myProgram.py because my program requires root privileges.

To execute the same from Visual Studio Code IDE, I tried prefixing the pythonPath variable in launch.json file with the sudo command but I get the following error:

Error: spawn sudo /usr/local/bin/python3 ENOENT

Here is my task configuration

{
    "name": "Python",
    "type": "python",
    "request": "launch",
    "stopOnEntry": true,
    "pythonPath": "sudo /usr/local/bin/python3",
    "program": "${file}",
    "cwd": "${workspaceFolder}",
    "env": {},
    "envFile": "${workspaceFolder}/.env",
    "debugOptions": [
        "RedirectOutput"
    ]
}
like image 342
user3626733 Avatar asked Nov 25 '25 00:11

user3626733


1 Answers

There is now a sudo option for Python debug configurations:

When set to true and used with "console": "externalTerminal", allows for debugging apps that require elevation. Using an external console is necessary to capture the password.

It is false by default, so you need to add it to your launch.json and set it to true:

{
    "name": "run-python-script-with-sudo",
    "type": "python",
    "request": "launch",
    "cwd": "${workspaceFolder}",
    "program": "/path/to/script.py",
    "console": "externalTerminal",
    "sudo": true
}

Do note that it will use the same Python interpreter you configured for your workspace. To override that and set a different Python interpreter, add the python option:

To use a different interpreter, specify its path instead in the python property of a debug configuration.

like image 118
Gino Mempin Avatar answered Nov 27 '25 14:11

Gino Mempin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!