3

I have created the following situation:

I have a cronjob that runs some python code and it crashes. Consider this code:

import json

uno = 1
print json.loads(uno)

I receive the following traceback:

Traceback (most recent call last):
  File "thiswillbreak.py", line 4, in <module>
    print json.loads(uno)
  File "/usr/lib/python2.7/json/__init__.py", line 326, in loads
    return _default_decoder.decode(s)
  File "/usr/lib/python2.7/json/decoder.py", line 366, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
TypeError: expected string or buffer

Is there anyway for me to also receive a list of all the variables in the scope so that I can debug this on the fly instead of attempting to reproduce the scenario? Obviously hard-coded values are easy, but if this value is obtained from some other place - debugging gets harder.

In particular I'm also using Django, which I know has loggers, but I couldn't find any information on how to enable variable printing. I only found how to hide sensitive variables, which isn't a problem because I don't see any variables at all.

Mikhail
  • 8,692
  • 8
  • 56
  • 82
  • take a look at python's logging tutorial (http://docs.python.org/2/howto/logging.html) -- you won't get an automatic list of *every* variable in scope, but you can log specific variables with specific messages. – Colleen Jul 18 '13 at 17:41

2 Answers2

2

As the best practice you should avoid dubug info in your output or exceptions, there are tools to help you with that. Here's an example:

enter image description here

Have a look at some related packages. For simple usage you might pick traceback-with-variables (pip install traceback-with-variables), here is it's postcard

enter image description here

Or try tbvaccine, or better-exceptions, or any other package

Bob Whitelock
  • 167
  • 3
  • 12
Kroshka Kartoshka
  • 1,035
  • 5
  • 23
1

You could also take a look at Python's builtin function locals(). This will probably work for simple cases, although I'm not sure how robust of a solution it will be. Generally speaking, going from object -> variable name isn't possible in python.

import json

dos = 2

def foo():
    uno = 1
    tres = 3

    try:
        json.loads(uno)
    except:
        print locals()

foo()
>>> {'uno': 1, 'tres': 3}
Community
  • 1
  • 1
FastTurtle
  • 2,301
  • 19
  • 19
  • I've seen people use some interactive debug toolbar for django that shows variables in use during the uncaught exception, so I have a feeling it's possible; just can't find it. – Mikhail Jul 18 '13 at 20:40