最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

python中使用sys模板和logging模塊獲取行號(hào)和函數(shù)名的方法

 更新時(shí)間:2014年04月15日 11:03:41   作者:  
這篇文章主要介紹了python中使用sys模板和logging模塊獲取行號(hào)和函數(shù)名的方法,需要的朋友可以參考下

對(duì)于python,這幾天一直有兩個(gè)問(wèn)題在困擾我:
1.python中沒(méi)辦法直接取得當(dāng)前的行號(hào)和函數(shù)名。這是有人在論壇里提出的問(wèn)題,底下一群人只是在猜測(cè)python為什么不像__file__一樣提供__line__和__func__,但是卻最終也沒(méi)有找到解決方案。
2.如果一個(gè)函數(shù)在不知道自己名字的情況下,怎么才能遞歸調(diào)用自己。這是我一個(gè)同事問(wèn)我的,其實(shí)也是獲取函數(shù)名,但是當(dāng)時(shí)也是回答不出來(lái)。


但是今晚!所有的問(wèn)題都有了答案。
一切還要從我用python的logging模塊說(shuō)起,logging中的format中是有如下選項(xiàng)的:

復(fù)制代碼 代碼如下:

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

也就是說(shuō),logging是能夠獲取到調(diào)用者的行號(hào)和函數(shù)名的,那會(huì)不會(huì)也可以獲取到自己的行號(hào)和函數(shù)名呢?
我們來(lái)看一下源碼,主要部分如下:

復(fù)制代碼 代碼如下:

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)

我簡(jiǎn)單解釋一下,實(shí)際上是通過(guò)在currentframe函數(shù)中拋出一個(gè)異常,然后通過(guò)向上查找的方式,找到調(diào)用的信息。其中

復(fù)制代碼 代碼如下:

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

的三個(gè)值分別為文件名,行號(hào),函數(shù)名。(可以去http://docs.python.org/library/sys.html來(lái)看一下代碼中幾個(gè)系統(tǒng)函數(shù)的說(shuō)明)
OK,如果已經(jīng)看懂了源碼,那獲取當(dāng)前位置的行號(hào)和函數(shù)名相信也非常清楚了,代碼如下:

復(fù)制代碼 代碼如下:

#!/usr/bin/python
# -*- coding: utf-8 -*-
'''
#=============================================================================
#  FileName:        xf.py
#  Description:     獲取當(dāng)前位置的行號(hào)和函數(shù)名
#  Version:         1.0
#=============================================================================
'''
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()

輸入結(jié)果是:
復(fù)制代碼 代碼如下:
('callfunc', 24)

符合預(yù)期~~
哈哈,OK!現(xiàn)在應(yīng)該不用再抱怨取不到行號(hào)和函數(shù)名了吧~

=============================================================================
后來(lái)發(fā)現(xiàn),其實(shí)也可以有更簡(jiǎn)單的方法,如下:

復(fù)制代碼 代碼如下:
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()

調(diào)用結(jié)果是:
復(fù)制代碼 代碼如下:
get_cur_info
<module>

相關(guān)文章

  • Python 使用PyQt5 完成選擇文件或目錄的對(duì)話框方法

    Python 使用PyQt5 完成選擇文件或目錄的對(duì)話框方法

    今天小編就為大家分享一篇Python 使用PyQt5 完成選擇文件或目錄的對(duì)話框方法。具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧
    2019-06-06
  • 用python生成1000個(gè)txt文件的方法

    用python生成1000個(gè)txt文件的方法

    今天小編就為大家分享一篇用python生成1000個(gè)txt文件的方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧
    2018-10-10
  • 使用pickle存儲(chǔ)數(shù)據(jù)dump 和 load實(shí)例講解

    使用pickle存儲(chǔ)數(shù)據(jù)dump 和 load實(shí)例講解

    今天小編就為大家分享一篇使用pickle存儲(chǔ)數(shù)據(jù)dump 和 load實(shí)例講解,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧
    2019-12-12
  • python ftplib上傳文件名亂碼的解決辦法

    python ftplib上傳文件名亂碼的解決辦法

    本文主要介紹了python ftplib上傳文件名亂碼的解決辦法,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧
    2025-04-04
  • python實(shí)現(xiàn)錄屏功能(親測(cè)好用)

    python實(shí)現(xiàn)錄屏功能(親測(cè)好用)

    這篇文章主要介紹了使python實(shí)現(xiàn)錄屏功能(親測(cè)好用),本文通過(guò)實(shí)例代碼給大家介紹的非常詳細(xì),對(duì)大家的工作或?qū)W習(xí)具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2020-03-03
  • Python裝飾器原理與簡(jiǎn)單用法實(shí)例分析

    Python裝飾器原理與簡(jiǎn)單用法實(shí)例分析

    這篇文章主要介紹了Python裝飾器原理與簡(jiǎn)單用法,結(jié)合實(shí)例形式分析了Python裝飾器的概念、原理、使用方法及相關(guān)注意事項(xiàng),需要的朋友可以參考下
    2018-04-04
  • 淺談Pandas中map, applymap and apply的區(qū)別

    淺談Pandas中map, applymap and apply的區(qū)別

    下面小編就為大家分享一篇淺談Pandas中map, applymap and apply的區(qū)別,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧
    2018-04-04
  • python3解析庫(kù)lxml的安裝與基本使用

    python3解析庫(kù)lxml的安裝與基本使用

    lxml是python的一個(gè)解析庫(kù),支持HTML和XML的解析,支持XPath解析方式,下面這篇文章主要給大家介紹了關(guān)于python3解析庫(kù)lxml的安裝與使用的相關(guān)資料,文中通過(guò)示例代碼介紹的非常詳細(xì),需要的朋友可以參考下
    2018-06-06
  • Python中tkinter開(kāi)發(fā)的常用29種功能用法總結(jié)

    Python中tkinter開(kāi)發(fā)的常用29種功能用法總結(jié)

    tkinter(Tk?interface)是Python的標(biāo)準(zhǔn)GUl庫(kù),支持跨平臺(tái)的GUl程序開(kāi)發(fā),本文為大家整理了tkinter開(kāi)發(fā)時(shí)常用的29種功能用法,希望對(duì)大家有所幫助
    2023-05-05
  • 最炫Python煙花代碼全解析

    最炫Python煙花代碼全解析

    2022虎年新年即將來(lái)臨,小編為大家?guī)?lái)了一個(gè)利用Python編寫(xiě)的虎年煙花特效,堪稱全網(wǎng)最絢爛,文中的示例代碼簡(jiǎn)潔易懂,感興趣的同學(xué)可以動(dòng)手試一試
    2022-02-02

最新評(píng)論

乐陵市| 天柱县| 揭阳市| 贡山| 潞城市| 长岭县| 巴林右旗| 金溪县| 绩溪县| 襄樊市| 沂水县| 湘潭县| 长沙市| 绥芬河市| 怀来县| 嘉黎县| 东兴市| 宣恩县| 鄂托克旗| 闻喜县| 雅安市| 儋州市| 海伦市| 玉树县| 泸定县| 沭阳县| 志丹县| 顺昌县| 泾阳县| 南部县| 汽车| 石城县| 永胜县| 阿荣旗| 鲜城| 汝阳县| 岢岚县| 安陆市| 曲水县| 贡山| 南陵县|