【发布时间】:2010-06-02 17:10:31
【问题描述】:
我正在为一个大学项目使用一段自修改代码。
这里是:
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()
不幸的是,它不起作用。返回错误:
# This is the script's output
This program is last run at Mon Jun 8 16:31:27 2009
# This is the error message
Traceback (most recent call last):
File "C:\Users\Rui Gomes\Desktop\teste.py", line 30, in <module>
main()
File "C:\Users\Rui Gomes\Desktop\teste.py", line 13, in main
srcfile = inspect.getsourcefile(sys.modules[__name__])
File "C:\Python31\lib\inspect.py", line 439, in getsourcefile
filename = getfile(object)
File "C:\Python31\lib\inspect.py", line 401, in getfile
raise TypeError('{!r} is a built-in module'.format(object))
TypeError: <module '__main__' (built-in)> is a built-in module
感谢您提供任何解决方案。
【问题讨论】:
-
自修改代码是邪恶的。任何语言。
-
检查你的路径,你是从 IDLE 2.5.6 调用 \Python31\lib 资源吗?
-
哇,这是个坏主意。为什么不能在其他地方记录运行时?
-
这只是概念证明。学术好奇心。
-
而且很难调试。你还需要什么证据证明这是个坏主意?
标签: python python-idle python-2.5 self-modifying