Debugging Azure Functions in PyCharm

I’ve been doing a fair amount of work recently involving Azure Functions using Python. Microsoft seem quite keen for us to use Visual Studio Code. I’m not so keen. I want to use PyCharm, but it took me a while to figure out how to get a debugger wired up. Hopefully this little demo will save the pain I went through. It turns out, like so many things, it’s easy when you know how. The secret is starting a remote debugger and connecting to it early in your Azure Function code.

In the terminal, initialize a new project, also installing the pydevd-pycharm package at the same time.

python -m venv venv
. ./venv/bin/activate
func init debugdemo -—worker-runtime python
cd debugdemo
func new --template “Http Trigger” --name debug
pip install pydevd-pycharm

Open the project in PyCharm. Add the virtual environment which was created above as the project interpreter (File→Settings→Project→Python Interpreter):

PyCharm Interpreter Settings
PyCharm Interpreter Settings

Add a new debug configuration of type ‘Python Debug Server’. Set your host name and port as required (note that we already installed the pydevd-pycharm package when we initialized the app):

Edit the function code, right at the top, include the code shown in the screenshot, e.g:

import pydevd_pycharm
pydevd_pycharm.settrace("localhost", port=12345, stdoutToServer=True, stderrToServer=True)

Start the debugger, set a breakpoint, then back in the terminal run func start as normal, and that’s it. Your breakpoint will be hit. Just remember to remove the code when you’re done.

Like I said, easy when you know how.