One day I got to wondering if it was possible to get a Python script to modify itself. After a few searches I found this 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 timestamp 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.

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()

I think the program should create a backup of itself before attempting to rewrite itself and restore the backup if anything goes wrong. It would be a minimal security feature if one wants to develop this.
IMHO, the main issue is that it is not very useful. A more standard procedure is that a program rewrites a configuration file and that this file is loaded when the program is executed. It is more robust, and it permits to reload the configuration file once it has been updated. Here reloading would mean restarting the program.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.