Methods for obtaining line numbers and function names using the SYS template and the logging module in Python _python

Source: Internet
Author: User
Tags time in milliseconds in python

For Python, there have been two problems that have plagued me these days:
There is no way to get the current line number and function name directly in 1.python. This is a question raised in the Forum, a group of people are just guessing why Python does not provide __line__ and __func__ like __file__, but ultimately did not find a solution.
2. If a function does not know its own name, how can you recursively call yourself. This is one of my colleagues asked me, but also to get the function name, but at that time was not answered.


But tonight! All the questions have an answer.
It's all going to start with the Python logging module, which has the following options in the format in logging:

Copy Code code 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 is 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 is issued
(if available)
% (funcName) s Function name
% (created) F time ' LogRecord was created (Time.time ()
return value)
% (asctime) s textual time is the LogRecord was created
% (msecs) d millisecond portion of the creation time
% (relativecreated) d time in milliseconds when the LogRecord is created,
Relative to the time the logging module is 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 of Record.getmessage (), computed just as
The record is emitted

In other words, logging is able to get to the caller's line number and function name, it will also be able to get their own line number and function name?
Let's take a look at the source code, the main part is as follows:

Copy Code code as follows:

Def currentframe ():
"" "Return to the frame object for the caller ' s stack frame." "
Try
Raise Exception
Except
return Sys.exc_info () [2].tb_frame.f_back
def findcaller (self):
"""
Find the stack frame of the "caller so" 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 calls
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
#IronPython can use logging.
Try
FN, Lno, func = Self.findcaller ()
Except 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)

Let me briefly explain, actually, by throwing an exception in the Currentframe function, and then finding the call by looking up. which

Copy Code code as follows:

RV = (Co.co_filename, F.f_lineno, Co.co_name)

The three values are file name, line number, function name, respectively. (You can go to http://docs.python.org/library/sys.html to see the description of several system functions in the code)
OK, if you have read the source code, then get the current position of the line number and function name is also very clear, the code is as follows:

Copy Code code as follows:

#!/usr/bin/python
#-*-Coding:utf-8-*-
'''
#=============================================================================
# FileName:xf.py
# Description: Gets the line number and function name of the current position
# version:1.0
#=============================================================================
'''
Import Sys
Def get_cur_info ():
"" "Return to the frame object for the caller ' s stack frame." "
Try
Raise Exception
Except
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 results are:
Copy Code code as follows:
(' Callfunc ', 24)

Meet the Expectations ~ ~
Haha, ok! Now you don't have to complain about getting the line number and function name.

=============================================================================
It turns out that there are more simple ways to do this, as follows:

Copy Code code 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 result of the call is:
Copy Code code 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.