Login

A smart trace() command

Author:
aparajita
Posted:
June 18, 2009
Language:
Python
Version:
1.0
Tags:
debugging
Score:
0 (after 0 ratings)

A number of people have kindly posted snippets on how to use pdb/ipdb with django. However, this only works when running the django development server.

I thought it would be nice to have a trace() command that would turn into a no-op when the development server is not running, so you wouldn't have to worry about leaving trace() commands in your code if you want to quickly test with mod_wsgi or mod_python.

The code above attempts (on Posix-like systems) to determine if the development server is running (by quickly checking if "manage.py runserver" is in the process list), and sets a DJANGO_SERVER setting appropriately. Then when you import the trace() method, it is defined as set_trace() if DJANGO_SERVER is True, or a no-op if DJANGO_SERVER is False.

When you hit the trace() in pdb/ipdb, enter "u" to go up to the calling trace() statement.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
In settings.py:

`# Try to determine if the django server is running
try:
	from commands import getoutput
	DJANGO_SERVER = getoutput('ps ax').find('manage.py runserver ') > 0
except ImportError:
	DJANGO_SERVER = False
`

In a file which you import:

`from django.conf import settings

if settings.DJANGO_SERVER:
	try:
		import ipdb as pdb
	except ImportError:
		import pdb
		
	def trace():
		pdb.set_trace()
else:
	def trace():
		pass
`

In the file in which you want to insert a trace:

from vs.utils import trace  # vs.utils is where you defined the method above

# some code
trace()

More like this

  1. pyserver -- runserver alias by presclark 6 years, 9 months ago
  2. Export Django data to datestamped tarball -- choose individual models for handy packaging and archiving by fish2000 4 years, 5 months ago
  3. Forcing unit test runner to abort after failed test by simonbun 7 years, 9 months ago
  4. showing environment variables in the django admin by tonemcd 5 years, 1 month ago
  5. Effective content caching for mass-load site using redirect feature by nnseva 3 years, 7 months ago

Comments

simon (on June 19, 2009):

This approach looks very risky to me - doesn't this mean that if you are using a separate runserver instance on your live server (which I sometimes do to fix bugs) your deployed instance will start firing up the debugger?

#

aparajita (on June 21, 2009):

Yes, you are correct. This was a quick and dirty hack to get the technique to work. I'm sure there are ways to make the test more robust so kind of thing you are talking about will be handled correctly.

#

Please login first before commenting.