Debug Python module using VS Code by pressing F5 - python

My project structure is as follows:
Project Folder
--setup.py
----Module Folder
------ __init__.py
------ __main__.py
My __main__.py file contains the entry point to my application and the setup file is configured like this:
from setuptools import setup
setup(name='my_project',
version='0.1.0',
packages=['my_project'],
entry_points={
'console_scripts': [
'my_project= my_project.__main__:main'
]})
This means I can run my code without the debugger attached using:
python -m my_project
I've tried debugging using VS Code by navigating to my __main__.py file and pressing F5 to run but this doesn't work and throws an exception. How do I configure Visual Studio Code to run this module in debug mode?
Also how do I ensure the program also runs the module and not the file I am looking at when I press F5?

The accepted answer didn't work for me (VSCode 1.49.0), and I got an error message reading: Invalid message: "program", "module", and "code" are mutually exclusive.
Removing the "program": "${file}", line solved the issue. I think this makes sense, since defining both a module (with an implied entrypoint) and a file is redundant.
My launch.json looks like this:
{
"version": "0.2.0",
"configurations": [
{
"name": "Python Module",
"type": "python",
"request": "launch",
"console": "integratedTerminal",
"module": "my_project",
}
]
}

After some research I've found a solution:
Navigate to the top right section in the debug menu and click the cog to create a launch.json file for this project. This will be used to configure VS Code.
If there isn't one already a launch.json file be created, into it paste this:
{
"version": "0.2.0",
"configurations": [
{
"name": "Python Module",
"type": "python",
"request": "launch",
"program": "${file}",
"console": "integratedTerminal",
"pythonPath": "${config:python.pythonPath}",
"module": "my_project",
"cwd": "${workspaceRoot}",
}
]
}
I found this code here: https://github.com/DonJayamanne/pythonVSCode/issues/518#issuecomment-260838308
Just using this answer didn't work for me though and I got the error: No module named my_projectbut I found this answer: https://github.com/DonJayamanne/pythonVSCode/issues/826
In it the final comment tells you add the following to the config.
"env": {"PYTHONPATH":"${workspaceRoot}"},
This fixes the error and now you can press F5 and your module will be debugged.

Related

Visual studio code - Python debug gives "No module named...." error

Ik have created a python test file in VSC. When I run this file it works fine and I see my output in the browser (Dash/Flask). However when I try to debug the file in VSC it gives me an error "No module named test.py" For sure I select the Python debug option.
My file structure is:
-root
-chapter
-test.py
What is the difference in debug and not debug?
Please check your launch.json. I have attached mine as a simple reference.
"version": "0.2.0",
"configurations": [
{
"name": "Python: Current File",
"type": "python",
"request": "launch",
"program": "${file}",
"console": "integratedTerminal",
"justMyCode": true,
}
]
By the way, you can debug here
I tried some options. In the end this worked for me: "cwd": "${fileDirname}",

Debug pipenv tasks.py task in vscode?

I've inherited a python project that I can start via pipenv invoke app.start. It looks like app.start is defined in a tasks.py.
How can I set up vscode to debug this project so I can set breakpoints?
I've got the venv selected as my interpreter in vscode.
Thanks!
The entry point to invoke is a Python script that should be in your virtual environment's bin directory (on the same level as the python file). E.g. /Users/<user>/.virtualenvs/<virtual-env>/bin/invoke.
If you have the path to your Python interpreter, you can replace python with invoke in the "program" value below.
You can create a Python VS Code debugging configuration (launch.json) as follows to run the invoke script with any given arguments in the "args" value:
{
"version": "0.2.0",
"configurations": [
{
"name": "Start app",
"type": "python",
"request": "launch",
"cwd": "${workspaceFolder}",
"program": "path/to/virtualenv/invoke",
"args": ["app.start"],
"console": "integratedTerminal",
"stopOnEntry": false,
},
]
}

python vs-code run file.py in file.py directory

Hi everyOne i'm trying to migrate to vscode from spyder. There is a way to configure the vsCode to run the curren opend file.py in the file.py folder automatically (not having to change manually the folder for every new file I open).
Second I have a file1.py containing some functions and main.py where I import file1. Is there a way to get autocompletion of functions in file inside the main?
Edit
launch.json
{
"version": "0.2.0",
"configurations": [
{
"name": "Python: Current File",
"type": "python",
"request": "launch",
"program": "${file}",
"console": "integratedTerminal",
"cwd" : "${workspaceFolder}/${relativeFileDirname}"
}
]
}

How can I debug Python console_script command line apps with the VSCode debugger?

I've a Python package package_name which provides a command line application command-line-app-name as console_script:
setup.py:
setup(
...
entry_points={"console_scripts": ["command-line-app-name=package_name.cli:main"]},
...
)
The virtualenv is located in <project>/.venv and managed with pipenv. pipenv managed venvs should support VSCode debugging integration. I've created a debugger configuration launch.json file with setting the Python path to the venv (pythonPath):
{
// 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: command-line-app-name",
"type": "python",
"request": "launch",
"stopOnEntry": false,
"program": "command-line-app-name",
"linux": {
"pythonPath": "${workspaceFolder}/.venv/bin/python",
"args": ["-r", "/home/florian/gitlab/package_name/data/Test_MRM.d"]
},
"windows": {
"pythonPath": "${workspaceFolder}/.venv/Scripts/python.exe",
"args": ["-r", "D:\\MassHunter\\Data\\demo_0000.d"],
},
"console": "integratedTerminal"
}
]
}
The Windows and Linux specific venv python executable and command line arguments should not have an impact. If I run the debugger I get: FileNotFoundError: [Errno 2] No such file or directory: '/home/florian/gitlab/package-name/command-line-app-name'. It seems like I'm miss-interpreting the documentation somehow. I tried to find help w.r.t. vscode-python as well as debugpy without success. How can I debug a console script command line app (instead of a package module)?
console_scripts cannot be debugged out-of-the-box. The solution is to call the entry point function directly instead ("program": "${workspaceRoot}/package_name/cli.py",). This requires to add the if __name__ == '__main__': idiom in the corresponding module (here: cli.py). In my case the command line argument parser used is click. However the pseudo-code should be very similar for other command line parser libs.
package_name/cli.py:
#click.command()
#click.option(...)
def main(<args>, <kwargs>):
...
if __name__ == '__main__':
main() # pylint: disable=no-value-for-parameter
.vscode/launch.json:
{
// 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: command-line-app-name",
"type": "python",
"request": "launch",
"stopOnEntry": false,
"program": "${workspaceRoot}/package_name/cli.py",
"linux": {
"pythonPath": "${workspaceFolder}/.venv/bin/python",
"args": ["-r", "/home/florian/gitlab/package_name/data/Test_MRM.d"]
},
"windows": {
"pythonPath": "${workspaceFolder}/.venv/Scripts/python.exe",
"args": ["-r", "D:\\MassHunter\\Data\\demo_0000.d"],
},
"console": "integratedTerminal"
}
]
}
NOTE: The tool used to manage the venv makes a difference. This solution does work in case the venv is managed with pipenv. The solution does not work in case the venv is managed with poetry.
Here is a launch.json that worked for me to debug mkdocs plugins:
{
"version": "0.2.0",
"configurations": [
{
"name": "Python: Module",
"type": "python",
"request": "launch",
"console": "integratedTerminal",
"module": "mkdocs",
"args": ["serve"]
}
]
}
mkdocs provides the mkdocs entry point that accepts several arguments such as build and serve. This launch.json allowed me to set a breakpoint in a mkdocs plugin python file and stop at that breakpoing after running the mkdocs build/serve process.

I got a wrong directory using os.path.abspath('.') [duplicate]

How do I run a Python program under debug and set the working directory for the run?
#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.
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}"
},
//... 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
Configure the cwd setting in launch.json as follows:
{
"name": "Python",
"type": "python",
"pythonPath": "python",
...
"cwd": "<Path to the directory>"
...
}
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
}
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}"
}
}
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
}
]
}
You can set up current working directory for debugged program using cwd argument in launch.json
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
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.
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}" }
]
}

Categories

Resources