删除py文件并保留pyc文件会破坏检查代码

时间:2014-06-26 12:31:50

标签: python bytecode inspect

以下功能正常。但是,如果我删除所有py个文件(并保持pyc完好无损),那么我会收到错误:

要解释我所说的'完整'是什么意思,或多或少是我所做的: 1.写一堆py文件并将它们粘贴在友好的目录结构中 2.测试代码。有用 3.编译所有py文件以获取pyc文件 4.删除py文件 5.测试代码。它失败了

功能:

def get_module_name_and_line():
    """
    return the name of the module from which the method calling this method was called.
    """
    import inspect
    lStack = inspect.stack()
    oStk = lStack[2]
    oMod = inspect.getmodule(oStk[0])         
    oInfo = inspect.getframeinfo(oStk[0])
    sName = oMod.__name__    #<<<<<<<<<<<<<<<<<< ERROR HERE
    iLine = oInfo.lineno
    return sName,iLine 

错误:

AttributeError: 'NoneType' object has no attribute '__name__'

因此错误中oModNone。如果py文件在,那么oMod永远不会None

问题:

如果py文件完好无损,为什么inspect只返回模块?如何在没有py文件的情况下使这个功能工作。

完整追溯:

Original exception was:
Traceback (most recent call last):
File "/home/criticalid/programs/damn.py", line 630, in <module>
File "/home/criticalid/programs/golly/class_foo.py", line 121, in moo
File "/home/criticalid/programs/golly/class_foo.py", line 151, in get_module_name_and_line
AttributeError: 'NoneType' object has no attribute '__name__'

1 个答案:

答案 0 :(得分:0)

这对我有用。它假定所有模块都在当前工作目录中的包中。并且它不会返回__main__模块,而是返回其文件名。

我确信有更好的解决方案,但这解决了我的问题。

def get_module_name_and_line():
    """
    return the name of the module from which the method calling this method was called.
    """
    def get_name_from_path(sPath):
        import os
        sCWD = os.getcwd()
        lCWD = list(os.path.split(sCWD))
        lPath = list(os.path.split(sPath))
        lPath[-1] = '.'.join(lPath[-1].split('.')[:-1])   #remove file extension
        lRet = [s for s in lPath[len(lCWD)-1:]]
        return '.'.join(lRet)

    import inspect
    lStack = inspect.stack()
    oStk = lStack[2]
    iLine = inspect.getlineno(oStk[0])
    sName = get_name_from_path(inspect.getfile(oStk[0]))
    return sName,iLine