我正在为一个大学项目使用一段自我修改的代码。在
这里是:
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}$我很感激任何解决办法。在
您可以使用
__file__
全局属性来获取当前模块的源路径。在从2.6文件中:
编辑:
我假设inspect.getsourcefile文件()在检查
__main__
模块时总是抛出TypeError。只有从交互式解释器运行时才会出现这种情况。我站在正确的立场上。德普。在它在IDLE之外运行时运行得非常好,因此问题不在代码本身,而是在执行它的环境中。当您在空闲状态下运行代码的错误部分时,您将得到以下输出:
当您在空闲状态下运行此
^{pr2}$您实际上是在试图修改
'C:\\Python26\\Lib\\idlelib\\idle.pyw'
。。。哪个懒汉不会让你这么做的。在长的和短的似乎是你写的确实起了的作用:但它不能在空闲状态下运行。在
相关问题 更多 >
编程相关推荐