Return to Snippet

Revision: 69278
at May 22, 2015 16:45 by BustACode


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

Initial URL


Initial Description
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&#

Initial Title
Python - Self-Modding Code

Initial Tags
python

Initial Language
Python