Using the sys template and the logging module in python to obtain the row number and function name

Source: Internet
Author: User
Tags time in milliseconds

For python, two problems have plagued me over the past few days:
1. The current row number and function name cannot be obtained directly in python. This is a question raised by someone in the forum. the people below are just wondering why python does not provide _ line _ and _ func __like _ file __, however, no solution was found.
2. How can a function call itself recursively without knowing its name. A colleague of mine asked me this question. In fact, I also obtained the function name, but I couldn't answer it at the time.


But tonight! All questions have answers.
Everything starts with using the python logging module. The format in logging has the following options:

Copy codeThe Code is as follows:
% (Name) s Name of the logger (logging channel)
% (Levelno) s Numeric logging level for the message (DEBUG, INFO,
WARNING, ERROR, CRITICAL)
% (Levelname) s Text logging level for the message ("DEBUG", "INFO ",
"WARNING", "ERROR", "CRITICAL ")
% (Pathname) s Full pathname of the source file where the logging
Call was issued (if available)
% (Filename) s Filename portion of pathname
% (Module) s Module (name portion of filename)
% (Lineno) d Source line number where the logging call was issued
(If available)
% (FuncName) s Function name
% (Created) f Time when the LogRecord was created (time. time ()
Return value)
% (Asctime) s Textual time when the LogRecord was created
% (Msecs) d Millisecond portion of the creation time
% (RelativeCreated) d Time in milliseconds when the LogRecord was created,
Relative to the time the logging module was loaded
(Typically at application startup time)
% (Thread) d Thread ID (if available)
% (ThreadName) s Thread name (if available)
% (Process) d Process ID (if available)
% (Message) s The result of record. getMessage (), computed just
The record is emitted

That is to say, logging can get the caller's row number and function name. Can it also get its own row number and function name?
Let's take a look at the source code. The main parts are as follows:

Copy codeThe Code is as follows:
Def currentframe ():
"Return the frame object for the caller's stack frame ."""
Try:
Raise Exception
Except t:
Return sys. exc_info () [2]. tb_frame.f_back
Def findCaller (self ):
"""
Find the stack frame of the caller so that we can note the source
File name, line number and function name.
"""
F = currentframe ()
# On some versions of IronPython, currentframe () returns None if
# IronPython isn' t run with-X: Frames.
If f is not None:
F = f. f_back
Rv = "(unknown file)", 0, "(unknown function )"
While hasattr (f, "f_code "):
Co = f. f_code
Filename = OS. path. normcase (co. co_filename)
If filename = _ srcfile:
F = f. f_back
Continue
Rv = (co. co_filename, f. f_lineno, co. co_name)
Break
Return rv
Def _ log (self, level, msg, args, exc_info = None, extra = None ):
"""
Low-level logging routine which creates a LogRecord and then CILS
All the handlers of this logger to handle the record.
"""
If _ srcfile:
# IronPython doesn' t track Python frames, so findCaller throws
# Exception on some versions of IronPython. We trap it here so that
# IronPython can use logging.
Try:
Fn, lno, func = self. findCaller ()
Failed t ValueError:
Fn, lno, func = "(unknown file)", 0, "(unknown function )"
Else:
Fn, lno, func = "(unknown file)", 0, "(unknown function )"
If exc_info:
If not isinstance (exc_info, tuple ):
Exc_info = sys. exc_info ()
Record = self. makeRecord (self. name, level, fn, lno, msg, args, exc_info, func, extra)
Self. handle (record)

In a simple explanation, an exception is actually thrown in the currentframe function, and the call information is found by searching up. Where

Copy codeThe Code is as follows:
Rv = (co. co_filename, f. f_lineno, co. co_name)

The three values are respectively the file name, row number, and function name. (You can go to http://docs.python.org/library/sys.htmlto check the description of several system regions in the Code)
OK. If you have understood the source code, you can obtain the row number and function name of the current location. The Code is as follows:

Copy codeThe Code is as follows:
#! /Usr/bin/python
#-*-Coding: UTF-8 -*-
'''
#===================================================== ==============================================
# FileName: xf. py
# Description: obtains the row number and function name of the current position.
# Version: 1.0
#===================================================== ==============================================
'''
Import sys
Def get_cur_info ():
"Return the frame object for the caller's stack frame ."""
Try:
Raise Exception
Except t:
F = sys. exc_info () [2]. tb_frame.f_back
Return (f. f_code.co_name, f. f_lineno)

Def callfunc ():
Print get_cur_info ()

 
If _ name _ = '_ main __':
Callfunc ()

The input result is:
Copy codeThe Code is as follows: ('callfunction', 24)
As expected ~~
Haha, OK! No need to complain that the row number and function name cannot be obtained ~

========================================================== ============================================
Later I found that there could be a simpler method, as shown below:
Copy codeThe Code is as follows: import sys
Def get_cur_info ():
Print sys. _ getframe (). f_code.co_name
Print sys. _ getframe (). f_back.f_code.co_name
Get_cur_info ()
The call result is:
Copy codeThe Code is as follows: get_cur_info
<Module>

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.