简体   繁体   中英

In Django/Python, how can I find out which method called my method?

I would the first line of my method to be:

print "this method was called from "+filename_and_linenumber_of_code_that_called_it.

Is it possible to throw an exception, catch it immediately, and print a stack trace when a method is called?

No need to throw an exception to view the stack. I have this nice function (it's not perfect, but I think it works) that may help you:

import inspect
def log(error):
  frame, filename, ln, fn, lolc, idx = inspect.getouterframes(inspect.currentframe())[1]
  print "Error: " + error + " " + filename, ln, fn

It prints the message followed by the name of the file that the parent function is in, then the line number of the call in this file, and then the name of the function. I hope it'll help you :)

When i just want to make the code crash at some point to see the traceback, i just put " crash " in the code. Because it's not defined, it will crash, and i will see the traceback in django's exception page. If in addition, i use runserver_plus command provided by django-extensions (requires package werkzeug ) then i get an AJAX shell at each frame of the stacktrace .

I understand you problem and I'm going to propose a professional method for dealing with this kind of problem. What you are trying to do is called " debugging " and there are tools for that.

Quickstart :

  1. run pip install ipython ipdb

  2. replace the print statement in your code by import ipdb; ipdb.set_trace() import ipdb; ipdb.set_trace()

  3. execute your code in runserver, it will pause and spawn a python shell where you can send command " up " to go to the previous stack frame (code that called your code) . Type l if you want to see more lines of code.

Longer start : well actually i wrote a an overview of tools which help debugging python and django .

I disagree with other answers which propose to add more elaborate print statement. You want to be a good developer: you want to use a debugger . Be it werkzeug, pdb/ipdb, or GUIs, it doesn't matter as long as you can use it.

This is CPython specific:

import sys

def func():
    frm = sys._getframe(1)
    print 'called from %s, line %s' % (frm.f_code.co_filename, frm.f_lineno)

def test():
    func()  # line 8

test()

Prints:

called from /path/to/script.py, line 8

A debugger like pdb can be helpful. Refer below snippet.

def f4():
    print "in f4"

def f3():
    import pdb
    pdb.set_trace()
    f4()
    print "in f3"

def f2():
    f3()
    print "in f2"

def f1():
    f2()
    print "in f1"

f1()

Once entered in pdb console, the up command can be entered to jump to the caller function.

Refer below screenshot. 在此输入图像描述

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM