2020-07-08 Update: Add notes for flask debug
As a Python programmer, you may have used pdb or Pycharm to debug your Python code.
But IMHO, those tools are a misunderstanding of Python language concepts. As Python is an interpreted language, it means we should abandon breakpoint and just tell the interpreter what we really want to do.
IPython is a powerful interactive Python shell, which has powerful tab completion and gives you access to talk with your program wherever you want to have a breakpoint.
This tool has too many dependencies and will pollute other libraries, so I recommend you use it with
virtualenv to split the environment.
You can use ipython in your shell environment or just add this to your program.
This is an example for embeding.
When you run it:
You can get the value of
a and when the debugging is over, exit
Here are some scenarios I have encountered at work.
IPython could save you time if you’re bothered by these scenarios.
Development phase: When you don’t know the return value of a function, or have questions about the data structure in the documentation, you can use IPython to look at the exact place in the code.
When you use
if-else, you could insert
IPython.embed()to watch what happend. Yes, the
IPython.embed()could be used in the except:
- Debug phase:
IPythoncould be used as breakpoint, which is more powerful than a breakpoint. You can execute some statements manually, including:
- statements that can be executed next
- unrelated statements, just for testing
Always remember to delete the embed statements before you
git add. It should not be used in the production environment, especially in tornado or uwsgi
for loop. It may go into interactive shell mode several times, and you may need
killto stop the program. If you really want this, please add a
IPythonin Windows. It is very slow. You could use WSL or virtual linux machine on it
If your program use uwsgi to start,
IPython.embed() could quit immediately. So I’ll give you two solution:
The first solution is to allow uwsgi work with stdin, and you could add this setting.
or just add this argument when you start
uwsgi --honour-stdin -y app.yaml
I have wrote another blog: Using Tornado to debug all types of Python servers, You can use Tornado to run servers that use the WSGI protocol.
After Tornado 6.0 version, use
IPython will cause
RuntimeError: This event loop is already running.
There is a simple solution for this, use
Actually, I use uwsgi in production mode, so I’d like to recommend you just keep use
I want to run a local server with beautiful log and autoreload support. You may only need a flask runner. so when in debug mode, you could use this:
# use tornado log support