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.
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:
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
Or try tbvaccine , or better-exceptions , or any other package
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}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.