Python代码段不适用于python2.5.6,使用IDLE

2024-05-23 22:55:25 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在为一个大学项目使用一段自我修改的代码。在

这里是:

import datetime
import inspect
import re
import sys

def main():
    # print the time it is last run
    lastrun = 'Mon Jun  8 16:31:27 2009'

    print "This program was last run at ",
    print lastrun

    # read in the source code of itself
    srcfile = inspect.getsourcefile(sys.modules[__name__])
    f = open(srcfile, 'r')
    src = f.read()
    f.close()

    # modify the embedded timestamp
    timestamp = datetime.datetime.ctime(datetime.datetime.now())
    match = re.search("lastrun = '(.*)'", src)
    if match:
        src = src[:match.start(1)] + timestamp + src[match.end(1):]

    # write the source code back
    f = open(srcfile, 'w')
    f.write(src)
    f.close()

if __name__=='__main__':
    main()

不幸的是,它不起作用。返回错误:

^{pr2}$

我很感激任何解决办法。在


Tags: therunimportresrcdatetimemainmatch
2条回答

您可以使用__file__全局属性来获取当前模块的源路径。在

从2.6文件中:

__file__ is the pathname of the file from which the module was loaded, if it was loaded from a file. The __file__ attribute is not present for C modules that are statically linked into the interpreter; for extension modules loaded dynamically from a shared library, it is the pathname of the shared library file.

编辑:

我假设inspect.getsourcefile文件()在检查__main__模块时总是抛出TypeError。只有从交互式解释器运行时才会出现这种情况。我站在正确的立场上。德普。在

它在IDLE之外运行时运行得非常好,因此问题不在代码本身,而是在执行它的环境中。当您在空闲状态下运行代码的错误部分时,您将得到以下输出:

>>> import inspect
>>> sys.modules[__name__]
<module '__main__' from 'C:\Python26\Lib\idlelib\idle.pyw'>
>>> inspect.getsourcefile(sys.modules[__name__])
'C:\\Python26\\Lib\\idlelib\\idle.pyw'

当您在空闲状态下运行此

^{pr2}$

您实际上是在试图修改'C:\\Python26\\Lib\\idlelib\\idle.pyw'。。。哪个懒汉不会让你这么做的。在

长的和短的似乎是你写的确实起了的作用:但它不能在空闲状态下运行。在

相关问题 更多 >