我正在为一个大学项目使用一段自修改代码。
这里是:
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
我会感谢任何解决方案。