删除py文件并保留pyc文件会导致检查代码失败

2 投票
1 回答
780 浏览
提问于 2025-04-18 11:10

下面这个函数运行得很好。但是如果我把所有的 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

这个方法对我有效。它假设所有的模块都在当前工作目录下的包里。而且它不会返回__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

撰写回答