Python - Code snippet not working on Python 2.5.6, using IDLE
Posted
by Francisco P.
on Stack Overflow
See other posts from Stack Overflow
or by Francisco P.
Published on 2010-06-02T17:10:31Z
Indexed on
2010/06/02
17:14 UTC
Read the original article
Hit count: 475
Hello, everyone
I am using a piece of self-modifying code for a college project.
Here it is:
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()
Unfortunately, it doesn't work. Error returned:
# 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
I'd be thankful for any solutions.
© Stack Overflow or respective owner