Search code examples
visual-studio-codesimplehttpserver

Start automatically python webserver from 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?


Solution

  • 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