日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > python >内容正文

python

python获取行号_在python中获取当前位置所在的行号和函数名

發布時間:2023/12/20 python 33 豆豆
生活随笔 收集整理的這篇文章主要介紹了 python获取行号_在python中获取当前位置所在的行号和函数名 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

python中沒辦法直接取得當前的行號和函數名。這是有人在論壇里提出的問題,底下一群人只是在猜測python為什么不像__file__一樣提供__line__和__func__,但是卻最終也沒有找到解決方案。

%(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 as the record is emitted

也就是說,logging是能夠獲取到調用者的行號和函數名的,那會不會也可以獲取到自己的行號和函數名呢?

def currentframe():

"""Return 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 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 calls

all the handlers of this logger to handle the record.

"""

if _srcfile:

#IronPython doesn't track Python frames, so findCaller throws an

#exception on some versions of IronPython. We trap it here so that

#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)

實際上是通過在currentframe函數中拋出一個異常,然后通過向上查找的方式,找到調用的信息。其中

rv = (co.co_filename, f.f_lineno, co.co_name)

的三個值分別為文件名,行號,函數名。(可以去http://docs.python.org/library/sys.html來看一下代碼中幾個系統函數的說明)

OK,如果已經看懂了源碼,那獲取當前位置的行號和函數名相信也非常清楚了,代碼如下:

#!/usr/bin/python

# -*- coding: utf-8 -*-

# Description: 獲取當前位置的行號和函數名

import sys

def get_cur_info():

"""Return 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()

輸入結果是:

('callfunc', 24)

符合預期~~

哈哈,OK!現在應該不用再抱怨取不到行號和函數名了吧~

=============================================================================

后來發現,其實也可以有更簡單的方法,如下:

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()

調用結果是:

get_cur_info

總結

以上是生活随笔為你收集整理的python获取行号_在python中获取当前位置所在的行号和函数名的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。