Start automatically python webserver from visual studio code - visual-studio-code

I would like to start automatically Python http.server when I'm hitting the run button (or F5) from visual studio code.
I assume it's the matter of the launch.json configuration but I'm not familiar with it.
How can I do that?

Please install the pythonVSCode extension. And create python file in your project directory. And place the below content on it. Refer here
import http.server
import socketserver
PORT = 8000
Handler = http.server.SimpleHTTPRequestHandler
with socketserver.TCPServer(("", PORT), Handler) as httpd:
print("serving at port", PORT)
httpd.serve_forever()
And create launch configuration like this...
{
"name": "Documentation",
"type": "python",
"request": "launch",
"stopOnEntry": false,
"pythonPath": "${workspaceRoot}/env/bin/python",
"program": "${workspaceRoot}/your_pyton_run_file.py",
"debugOptions": [
"WaitOnAbnormalExit",
"WaitOnNormalExit",
"RedirectOutput"
]
},
Then you can start this with F5

Related

How can I change the capitalization of the project directory VS Code passes when debugging?

I'm running a Next.JS project in VS Code. My launch.json has the following configuration:
{
// ...
"configurations": [
{
"name": "Frontend: Dev Server",
"request": "launch",
"runtimeArgs": [
"run-script",
"dev",
"--preserve-symlinks", // To debug linked
],
"runtimeExecutable": "npm",
"skipFiles": [
"<node_internals>/**"
],
"type": "node",
}
],
}
When I run this configuration from VS Code, I get an error like the following:
C:\Program Files\nodejs\npm.cmd run-script dev --preserve-symlinks
> web-client#0.1.0 dev
> next dev -p 5555
warn - Invalid casing detected for project dir, received c:\etcetc actual path C:\etcetc, see more info here https://nextjs.org/docs/messages/invalid-project-dir-casing
I know that I want VS Code to pass in the drive letter in upper case instead of lower case, but I don't see any option to set that and I tried opening the project using code C:\etcetc directly.
How can I change the capitalization of the directory that VS Code applies to the launch configuration?
Add a current working directory to your launch.json configuration:
{
// ...
"configurations": [
{
"cwd": "${workspaceFolder}",
"name": "Frontend: Dev Server",
// ...
}
]
}
This passed an upper case drive letter to Node for me. You may also want to check that VS Code is opening the folder with the right case, i.e. node C:\etcetc.
If you still have casing errors, try deleting the .next directory.

How to configure VS code for pytest with environment variable

I am trying to debug pytest. I would like to inject an environment variable. Here is how I have set launch.json
{
"type": "python",
"request": "test",
"name": "pytest",
"console": "integratedTerminal",
"env": {
"ENV_VAR":"RandomStuff"
}
},
But it seems when I start debugging. I do not see the env variable injected, as a result my test which expects that env variable fails.
Also I notice error
Could not load unit test config from launch.json
pytest-env
Install
Per https://stackoverflow.com/a/39162893/13697228:
conda install -c conda-forge pytest-env
Or:
pip install pytest-env
pytest.ini
Create pytest.ini file in project directory:
[pytest]
env =
ENV_VAR=RandomStuff
Python
In your code, load environment variables as you normally would:
import os
env_var = os.environ["ENV_VAR"]
pytest / VS Code
Either run:
pytest
(Notice how it says configfile: pytest.ini)
C:\Users\sterg\Documents\GitHub\sparks-baird\mp-time-split> pytest
==================================== test session starts ===================================== platform win32 -- Python 3.9.12, pytest-7.1.1, pluggy-1.0.0 rootdir:
C:\Users\sterg\Documents\GitHub\sparks-baird\mp-time-split,
configfile: pytest.ini plugins: anyio-3.6.1, cov-3.0.0, env-0.6.2
collecting ...
Or:
This only seems to work with breakpoints that have manually been set, I'm guessing some other change is needed to pause on errors.
Python for VS Code Extension
Apparently the Python for VS Code extension recognizes a .env file automatically. E.g.
.env file:
ENV_VAR=RandomStuff
Haven't verified, but I'd assume this has the same behavior as using pytest-env with a pytest.ini file.
When all else fails
When I don't feel like dealing with the strange hackery necessary to get VS Code, Anaconda environments, and pytest playing nicely together (and/or forget how I fixed it before), I call my tests manually and run it like a normal script (see below). This may not work with more advanced pytest trickery using fixtures for example. At the end of your Python script, you can add something like:
if __name__ == "__main__":
my_first_test()
my_second_test()
and run it in debug mode (F5) as normal.
Could not really figure out how to fix "unit" test debugging with Vscode. But with Pytest one can call tests like python -m pytest <test file>(https://docs.pytest.org/en/stable/usage.html#cmdline)
That means Vscode can be configured like a module
"configurations": [
{
"name": "Python: Module",
"type": "python",
"request": "launch",
"module": "pytest",
"args": ["--headful","--capture=no", "--html=report.html"],
}
This is good enough to do debugging of python tests. Also you can then insert environment variables
"env": {
"ENV_VAR":"RandomStuff"
}
This works in v 1.72.2
Create in the workspace folder:
.vscode/launch.json
Similar to the OP, but using "module"
{
"version": "0.2.0",
"configurations": [
{
"name": "Pytest",
"type": "python",
"request": "launch",
"module": "pytest",
"console": "integratedTerminal",
"env": {
"testy": "someval"
}
}
]
}
Try some breakpoints (either in test files or app code)
Start the debugger
Watch the os.environ['testy'] value (must import os where the breakpoint is of course)

Debug FastAPI application in VSCode

i'm trying to debug an application (a web api) that use FastAPI (uvicorn)
I'm also using poetry and set the projev virtual environment in vscode.
i read this tutorial to setup uvicorn and this one to setup vscode but i think i'm doing something wrong in set it up.
I tried to setup the launch.json both as python: module and python: current file
The problem seems that it doesn't recognize the project structure cause when i run the debug it stopped in an import statement with this error:
Exception has occurred: ImportError
attempted relative import with no known parent package
This is my current launch.json configuration:
"configurations": [
{
"name": "Python: local debug",
"type": "python",
"request": "launch",
"program": "${workspaceFolder}/src/topic_service/service/__init__.py",
"args" : ["--port", "8000"]
},
]
I also tried to add a .env file setting PYTHONPATH:
PYTHONPATH=.:${PYTHONPATH}
Locally i run the application as follow:
poetry run uvicorn src.main:app --port 8080 --reload
Does anyone know how to correctly setup vscode to debug an uvicorn application?
Thank you
UPDATE:
I also tried what this article says. the debugger seems to start but nothing happen (no breakpoint is triggered)
Try this configuration.
{
"name": "Python: Module",
"type": "python",
"request": "launch",
"module": "uvicorn",
"args": ["src.main:app","--reload"]
}
Likewise you provide uvicorn module with necessary args during development of FastAPI application, you need to configure your launch.json located in .vscode directory with respective values.
I did a write up for custom project configurations to debug FastAPI in VS Code here
Suppose you issue the following command to run FastAPI on uvicorn server with args mentioned as below
uvicorn main:app --reload --port 8000
then your launch.json should have module with value of uvicorn and each of the args separated by space as items of the args array.
"module": "uvicorn",
"type": "python",
"request": "launch",
"args": [
"main:app",
"--reload",
"--port",
"8000"
],
"env": {
"usersecret": "some$Ecret",
}
You can have this launch.json file in .vscode and then modify the args array in the JSON configuration as per your project structure.
{
// 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: FastAPI",
"type": "python",
"request": "launch",
"module": "uvicorn",
"env": {
"db_username": "postgres",
"db_password": "secret",
"host_server": "localhost",
"database_name": "fastapi",
"ssl_mode": "prefer",
"db_server_port": "5432"
},
"args": [
"main:app",
"--reload",
"--port",
"8000"
]
}
]
}
For me worked with this configurations:
On Debug section on VSCode, choose create launch.json option. Probally it will open launch.json on .vscode folder in your root folder explorer
like this, inside of launch.json put this:
"version": "0.2.0",
"configurations": [
{
"name": "Python: FastAPI",
"type": "python",
"request": "launch",
"module": "uvicorn",
"cwd": "${workspaceFolder}/<folder to your main.py>",
"args": [
"main:app",
"--reload",
"--port", //these arg are optional
"3003"
]
}
]
}
Now , just run your debugger and have a nice day!
Edit: The cwd ensure that your debbuger will find the right path to your main.py file. So, for whos use multiple debuggers or uses outside vsCode with launch.json it's a nice choice use it.
The quick and easy way: launch debugger F5 and then select FastAPI Debug Configuration:
(p.s. this works on the VSCode Insiders; haven't tried it on a regular version)
The way i debug is quite basic, hope it helps
i have .py file with this config:
import uvicorn
from app.main import api
if __name__ == "__main__":
dev = 1
if dev==0:
#use this one
uvicorn.run(api, host="127.0.0.1", port=5000, log_level="info")
if dev == 1:
#or this one
uvicorn.run('app.main:api', host="127.0.0.1", port=5000, log_level="info", reload=True, debug=True)
if dev == 2:
uvicorn.run('app.main:api', host="127.0.0.1", port=5000, log_level="info", workers=2)
and run the file with the vscode debugger, the important thing is to run the app with the debug flag because otherwise the debugger skips the breakpoints (at least in my case)

How to start both Angular app and WebApi service from VSCode on F5 or Ctrl+F5

I have top-level folder Homepage with the following structure:
--Homepage
----Client <- Angular app, created with `ng new` command
----Server <- .NET Core WebApi, created with `dotnet new webapi` command
I open VSCode at Homepage level:
I have these extensions installed:
Question
If I want to use single VSCode environment to work on both projects, Client and Server, is it possible to bind F5 (or Ctrl+F5) to start both projects together?
Client app I start using ng serve (it will run on http port 4200)
Server app I start using dotnet run (it will run on https port 5001)
I have just one common .vscode folder on Homepage (root level):
By default, when first created, the content of launch.json was this:
{
// Use IntelliSense to find out which attributes exist for C# debugging
// Use hover for the description of the existing attributes
// For further information visit https://github.com/OmniSharp/omnisharp-vscode/blob/master/debugger-launchjson.md
"version": "0.2.0",
"configurations": [
{
"name": ".NET Core Launch (web)",
"type": "coreclr",
"request": "launch",
"preLaunchTask": "build",
// If you have changed target frameworks, make sure to update the program path.
"program": "${workspaceFolder}/Server/bin/Debug/netcoreapp2.1/Server.dll",
"args": [],
"cwd": "${workspaceFolder}/Server",
"stopAtEntry": false,
"internalConsoleOptions": "openOnSessionStart",
"launchBrowser": {
"enabled": true,
"args": "${auto-detect-url}",
"windows": {
"command": "cmd.exe",
"args": "/C start ${auto-detect-url}"
},
"osx": {
"command": "open"
},
"linux": {
"command": "xdg-open"
}
},
"env": {
"ASPNETCORE_ENVIRONMENT": "Development"
},
"sourceFileMap": {
"/Views": "${workspaceFolder}/Views"
}
},
{
"name": ".NET Core Attach",
"type": "coreclr",
"request": "attach",
"processId": "${command:pickProcess}"
}
,]
}
So, when I press F5 it builds and start the Server app, the page opens at https://localhost:5001, from there I can navigate to https://localhost:5001/api/values and see WebApi works.
But the Client app doesn't start at all.
So, I thought if I add Debugger for Chrome extension's settings to launch.json, it should work, so I clicked on Add Configuration and added corresponding section:
{
"type": "chrome",
"request": "launch",
"name": "Launch Chrome",
"url": "http://localhost:4200",
"webRoot": "${workspaceFolder}"
},
I changed port from 8080 to 4200, since ng serve hosts on port 4200
But it does not start the Client app.
Please advice. Thanks
I have similar (node.js for API) and spent quite some times couldn't resolved, for example use && or &. Result is either API up or Angular up, never the both.
Anyway I finally realized have both Api and UI in the same folder/project/solution is not practical. An API is not specific to an UI, it's a universal DLL/service, should be siting somewhere by itself. So I separated them into two diff folders and have 2 VSC instances to run them:
start the API in debug mode
in 2nd VSC, run ng serve and let it take time to build
when ng says "Compiled successfully" go to launch.json to start the debug entry associated with Chrome
they work perfectly.

Cannot debug in VS Code by attaching to Chrome

I have default config in launch.json. The site runs on port 8080.
{
"version": "0.2.0",
"configurations": [
{
"type": "chrome",
"request": "launch",
"name": "Launch Chrome against localhost",
"url": "http://localhost:8080",
"webRoot": "${workspaceRoot}"
},
{
"type": "chrome",
"request": "attach",
"name": "Attach to Chrome",
"port": 9222,
"webRoot": "${workspaceRoot}"
}
]
}
However, when I click on the Debug button, I get this error:
Cannot connect to the target: connect ECONNREFUSED 127.0.0.1:9222
Question 1: Why does VS Code assign port 9222 when creating this json?
What is so special about this port that MS decided to put it in this launch.json?
Question 2: What do I need to change to make things work?
The Launch debug always launches a new window.
I am asking specifically about Attach debug option, so that it will open in a new tab instead.
When using the configuration url, vscode will search for a tab with the EXACT url and attach to it if found.
Use the configuration urlFilter, which can have wildcards like *, to attach the debugger to any sub route in your url.
e.g. "urlFilter": "http://localhost:4200/*"
The complete exacts steps to take:
configure your launch.json file to looks something like this:
{
"version": "0.2.0",
"configurations": [
{
"type": "chrome",
"request": "attach",
"name": "Attach to Chrome",
"port": 9222,
"urlFilter": "http://localhost:4200/*",
"webRoot": "${workspaceFolder}"
}
]
}
Close all opened chrome instances (make sure that all of them are killed using task manager in windows).
Launch chrome with the following parameter: --remote-debugging-port=9222
Make sure that the port in this parameter is the same as the one configured in 'port' property of the attache to chrome configuration in the launch.json file (like the example above)
You can add this parameter in your chrome shortcut properties by:
Right click your shortcut file and select properties
Chain it to Target property, e.g.
"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" --remote-debugging-port=9222
Navigate to your site. In this example, http://localhost:4200
Run 'Start debugging' in VS Code.
You need to install Debugger for Chrome extension for this to work. Open extensions in VS Code and search for Debugger for Chrome
You need to run a web server on the URL specified in the first configuration (default to http://localhost:8080). I use serve npm package that I installed globally. From my app folder I run serve -p 8080
Select Launch Chrome against localhost option. It will launch the browser and you can set breakpoints in your code and the debugging should work.
Regarding the second configuration (Attach to Chrome). There's nothing special about the port. In order to attach to Chrome you need to run Chrome with remote debugging enabled on port specified in the config. For example chrome.exe --remote-debugging-port=9222. I personally never use this options. Just follow the three steps above and you should be fine.
The Debugger for Chrome extension is deprecated. You do not need it anymore.
I came across this question when looking for help using the "Attach to Chrome" configuration in VSCode. While the accepted answer did give me a few hints, I did have to do some more digging. Here are the steps that worked for me in case anyone else finds them useful:
Install the Debugger for Chrome extension in VSCode Skip this, it's not needed anymore
Serve your files with a web server of your choice
Launch Chrome with remote debugging enabled
In this new Chrome window navigate to the url that your web server is hosting (http://localhost:8080 for example).
In VSCode, add a configuration to your launch.json file that looks like this:
"configurations": [
{
"type": "chrome",
"request": "attach",
"port": 9222,
"name": "Attach Chrome",
"url": "http://localhost:8080/",
"webRoot": "${workspaceFolder}"
}
]
Press the play button in VSCode with the 'Attach to Chrome' option selected from the drop down.
The key thing needed in the configuration file is the url field. This needs to be the URL where your files are being hosted and this URL needs to be currently open in the Chrome window that you just launched with remote debugging enabled. If you enter everything else right except this field, VSCode will give you an error message that says which urls are available. Something like Cannot connect to runtime process, timeout after 10000 ms - (reason: Can't find a valid target that matches: localhost:8080/. Available pages: ["http://localhost:8080",...
For the sake of completeness, here's how you launch Chrome with remote debugging enabled (from the Debugger for Chrome README):
Windows:
Right click the Chrome shortcut, and select properties
In the "target" field, append --remote-debugging-port=9222
Or in a command prompt, execute <path to chrome>/chrome.exe --remote-debugging-port=9222
MacOS:
In a terminal, execute /Applications/Google\ Chrome.app/Contents/MacOS/Google\ Chrome --remote-debugging-port=9222
Linux:
In a terminal, launch google-chrome --remote-debugging-port=9222
A 2020 complement answer...
VS Code has a new debug that is not stable yet but works as default on Insiders version at the moment.
It opens automatically a new Chrome instance with debugging for attached with these settings:
{
"name": "Attach to Chrome",
"port": 9222,
"request": "attach",
"type": "pwa-chrome",
"webRoot": "${workspaceFolder}/src"
}
Like any attached, you can run the debug any time at this new window opened by VS Code.
Or you can run the Chrome as debug mode previously to avoid the VS Code to open a new debug window just like #quicklikerabbit answer https://stackoverflow.com/a/51392142/7050878 but this time without the need of the URL parameter.
The following procedure is for React applications created by create-react-app:
Click the Extensions button in the Activity Bar and install the Debugger for Chrome extension if it's not already installed.
Open a new Terminal window. cd to the client folder if necessary and install chrome-launcher:
npm install chrome-launcher
Switch to the Debugger panel in the Side Bar.
Click the Configuration drop-down at the top of the Side Bar and choose "Add Configuration..." Alternatively, press the little gear icon at the top of the Side Bar to open launch.json and then press the big blue button labeled "Add Configuration..."
From the list of configuration templates, choose Chrome: Attach. The following configuration should be added to launch.json:
{
"name": "Attach to Chrome",
"port": 9222,
"request": "attach",
"type": "pwa-chrome",
"webRoot": "${workspaceFolder}"
},
There's no need to change anything in this configuration.
Add a new file named .env with the following content to the root folder of your project (or to the root of the client folder if it's a full-stack application):
BROWSER=launchChrome.js
Add a new file named launchChrome.js to the same folder, with the following content:
const chromeLauncher = require('chrome-launcher');
chromeLauncher.launch({
startingUrl: process.argv[2],
port: 9222,
}).then(function (chrome) {
console.info('Chrome remote debugging port:', chrome.port);
});
Launch your React app from the Terminal window:
npm start
After a few seconds, you should see the following text:
Starting the development server...
Chrome remote debugging port: 9222
At the top of the Side Panel, choose the configuration Attach to Chrome and press the green triangle.
You can now place breakpoints in your React code and the debugger will break when it hits them. You can even debug your server and your client simultaneously by adding a Node.js: Launch Program configuration to launch.json.
I will put my measly two cents in :) unfortunately or fortunately I had a similar problem and the above post pointed me in the right direction and I learned a little something along the way. Please see my notes below:
1) If you are on Linux, after starting vsCode run the following Linux command:
sudo lsof -i -P -n | grep LISTEN
this will allow you to see what ports are being used, in my case you can see code on 5500.
2) Assuming you have some test html/js code and vsCode has a server and debugger installed then the following files need to be configured as such:
code-workspace file:
/*
Workspace settings override user settings.
https://code.visualstudio.com/docs/getstarted/settings
Check to see if needed ports are listening: sudo lsof -i -P -n | grep LISTEN
*/
{
"folders": [
{
"path": "."
}
],
"settings": {
"liveServer.settings.AdvanceCustomBrowserCmdLine": "google-chrome-stable --remote-debugging-port=9222",
}
}
launch.json:
{
/*
Workspace settings override user settings.
https://code.visualstudio.com/docs/getstarted/settings
Check to see if needed ports are listening: sudo lsof -i -P -n | grep LISTEN
*/
"version": "0.2.0",
"configurations": [
{
"name": "Launch 127.0.0.1:5500",
"type": "chrome",
"request": "launch",
"url": "http://127.0.0.1:5500/${relativeFileDirname}/${fileBasename}",
"webRoot": "${workspaceFolder}/${relativeFileDirname}"
},
{
"name": "Attach 127.0.0.1:5500",
"type": "chrome",
"request": "attach",
"port": 9222,
"url": "http://127.0.0.1:5500/${relativeFileDirname}/${fileBasename}",
"webRoot": "${workspaceFolder}/${relativeFileDirname}/"
},
]
}
setting.json:
/*
Workspace settings override user settings.
https://code.visualstudio.com/docs/getstarted/settings
Check to see if needed ports are listening: sudo lsof -i -P -n | grep LISTEN
*/
{
"cSpell.language": "en",
"git.enableSmartCommit": true,
"git.autofetch": true,
"[html]": {
"editor.defaultFormatter": "vscode.html-language-features"
},
"liveServer.settings.donotShowInfoMsg": true,
"cSpell.userWords": [
"lsof",
"readonly"
],
"[javascript]": {
"editor.defaultFormatter": "esbenp.prettier-vscode"
},
"cSpell.enabledLanguageIds": [
"asciidoc",
"c",
"cpp",
"csharp",
"css",
"git-commit",
"go",
"handlebars",
"haskell",
"html",
"jade",
"java",
"javascript",
"javascriptreact",
"json",
"jsonc",
"latex",
"less",
"markdown",
"php",
"plaintext",
"pug",
"python",
"restructuredtext",
"rust",
"scala",
"scss",
"text",
"typescript",
"typescriptreact",
"yaml",
"yml"
],
}
3) NOTE make sure all browsers are closed before starting up the 'Live Server'. Spin-up your server 'Live Server'to open the file you would like to debug as per the configuration for the chrome browser stipulated in the vsCode File>Preferences>Settings, NOTE use 127.0.0.1 I had no luck with localhost, also the default port is 5500. The browser is now launched as per the vsCode-workspace file setting "liveServer.settings.AdvanceCustomBrowserCmdLine": "google-chrome-stable --remote-debugging-port=9222", this is where the debug magic takes place. NOTE make sure all browsers are closed before starting up the 'Live Server'.
Especially check to make sure there are no chrome extension like Hangouts running, this will also prevent Chrome from opening port 9222, I had to click the Exit option on the task to kill all Chrome extension in my example:
4) Now if you run sudo lsof -i -P -n | grep LISTEN you will see vsCode 'Live Server' serving on port 127.0.0.1:5500 and the debugger doing its thing on port 127.0.0.1:9222; If you do not see both ports opened then something is not correct and you will need to confirm STEP 3) listed above.
5) You can check the web interface for the debugger by entering http://127.0.0.1:9222/ in a empty browser tab, this url will display links to every tab and extensions open and allow you to poke around with the debugger, click on the link to the file you want to debug, in my case 127.0.0.1:5500/Leason_66/index.html, this is the port and link vsCode will communicate with and re-render in the IDE Debugger.
6) Note: Make sure you are on the file you want to debug. We are almost there, now just click on the Debug Icon then go to the GREEN Play Button and select the attach option from the drop down, please note the information configured in the launch.js file is what will appear in the drop down.
7) Time for some action! Now all you have to do is click on the GREEN Play Button and the Debugger will now attach to tab you have open at 127.0.0.1:5500/<path you your file> and do its debug on port 127.0.0.1:9222
8) Happy Engineering :)
Try this:
"type": "edge",
"request": "launch",
"name": "Launch Edge",
"url": "http://localhost:8080",
"webRoot": "${workspaceFolder}"
"file": "${workspaceFolder}/index.html"
Peek into Task Manager. You may have Chrome instances hanging there. Only after killing them will you be able to run the remote and successfully start the debugger.
Run Chrome on macOS without command lines.
We'll create a shortcut of Chrome that will run --remote-debugging-port=9222 for us.
Steps
Open the native application called Automator.
It opens a selector. Our goal is to create an application, hence we choose Application.
Look for shell.
Add the next script /Applications/Google\ Chrome.app/Contents/MacOS/Google\ Chrome --remote-debugging-port=9222
Then save it with your desire. Our application shortcut is done.
Run the Spotlight with CMD + Space and type your app name, mine starts with Chrome Debug. Open it and voilĂ 
Add the launch.json this configuration (you can edit the localhost's port):
{
"name": "Chrome lh:4200",
"type": "chrome",
"request": "attach",
"urlFilter": "http://localhost:4200/*",
"port": 9222,
"webRoot": "${workspaceFolder}"
}
Run that debug configuration. VSCode is waiting. Open your localhost URL on the Chrome, VSCode debugger will show this state: