Python - Self-Modding Code


/ Published in: Python
Save to your folder(s)

One day I got to wondering if it was possible to get a Python script to modify itself. After a few searches I found a solution that I present here. I did not write this code, but feel that it should be "paid forward" so others know that it is possible, and how to accomplish it. Basically the script reads itself into a variable, then REs the time stamp line which is then replaces with a new one. Next the modified code is saved back down. I could actually see a genetic algo modding itself as it goes so that it writes an optimal version of itself at the end. Pretty cool. NOTE: A backup function should be added for safety.
Original code site: http://showmedo.com/videotutorials/video?name=7610000&#


Copy this code and paste it in your HTML
  1. import sys, os, importlib, inspect, locale, time, re, inspect, datetime
  2. from datetime import datetime
  3. locale.setlocale(locale.LC_ALL, '') # Set the locale for your system 'en_US.UTF-8'
  4. # Main #
  5. def main():
  6. # Main Code
  7. # Print the time it is last run
  8. lastrun = 'Tue Mar 3 03:17:46 2015'
  9. print("This program was last run at: <<%s>>.") %(lastrun)
  10. # Read in the source code of itself
  11. srcfile = inspect.getsourcefile(sys.modules[__name__]) ## Gets module name and path then extracts and stores file name and path.
  12. print("DEBUG srcfile: %s") %(srcfile) # DEBUG
  13. f = open(srcfile, 'r') ## Open connections to source file in "r" mode and stores connection in "f".
  14. src = f.read() ## Reads source file code into "src" variable.
  15. f.close() ## Closes file connection.
  16. # modify the embedded timestamp
  17. timestamp = datetime.ctime(datetime.now())
  18. match = re.search("lastrun = '(.*)'", src)
  19. if match:
  20. src = src[:match.start(1)] + timestamp + src[match.end(1):]
  21. print("Here")
  22. # write the source code back
  23. f = open(srcfile, 'w')
  24. f.write(src)
  25. f.close()

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.