Name: [771] David Fung
Member: 88 months
Authored: 3 videos
Description: A programmer who enjoys programming. ...

Self-modifying code [ID:1483] (1/1)

in series: Self-modifying code

video tutorial by David Fung, added 06/09

(Showmedo is undergoing major changes. To report any problems viewing the videos please email us and include browser and OS specifics. Cheers - Kyran.)

Using the inspect and re modules, write a piece of code that update itself every time it is run.

The idea is come from the PEAK ez_setup.py script.

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 is last run at <<%s>>." % 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()

Got any questions?

Get answers in the ShowMeDo Learners Google Group.

Video statistics:

  • Video's rank shown in the most popular listing
  • Video plays: 743 (since July 30th)
  • Plays in last week: 3
  • Published: 63 months ago

Thank-yous, questions and comments

If this video tutorial was helpful please take some time to say thank-you to the authors for their hard work. Feel free to ask questions. Let the author know why their video tutorial was useful - what are you learning about? Did the video tutorial save you time? Would you like to see more?

You may also want to see our ShowMeDo Google Group to speak to our active users and authors.

Your email address will not be published.

Show some quick comments >>








All comments excluding tick-boxed quick-comments

Found watching how you went about it very interesting.


This program can't work correctly when executed in IDLE (or another IDE console):

Try in IDLE:

def main():

...

# read in the source code of itself

srcfile = inspect.getsourcefile(sys.modules[__name__])

print "This program file name is <%s>." % srcfile

...

IDLE 1.2 ==== No Subprocess ====

>>>

This program is last run at <<Mon Jun 8 16:31:27 2009>>.

This program file name is <C:\Python25\Lib\idlelib\idle.pyw>.

There is a solution => make and use simply module with 1 function for determ.name

___________MODULE = myInspect.py________________

import sys

def getFILE(FRAME=None,OLD=None):   # <<<<<!>

try:

NEW = FRAME.f_code.co_filename

return  NEW != OLD and OLD and NEW or getFILE(FRAME.f_back,NEW)

except AttributeError:

return  getFILE(sys.exc_info()[2].tb_frame,None)

________________________________________________

import datetime

import inspect

import re

import sys

import myInspect # <<<<<!>

def main():

# print the time it is last run

lastrun = 'Mon Jun  8 16:31:27 2009'

print "This program is last run at <<%s>>." % lastrun

# read in the source code of itself

srcfile = myInspect.getFILE()   # <<<<<!>

f = open(srcfile, 'r')

src = f.read()

f.close()

....


Great little technique there!


I copy the code to my computer and run it, why it raises the error:

File "C:\Python25\lib\inspect.py", line 383, in getsourcefile

filename = getfile(object)

File "C:\Python25\lib\inspect.py", line 347, in getfile

raise TypeError('arg is a built-in module')

TypeError: arg is a built-in module

Environment:Windows XP && python2.5


I think the potential of self modifying code is enormous and you've made it very easy, please produce more vids like this


6. anonymous Sun, 30 Aug 2009 05:15

I really enjoyed this tutorial. The use of the regular expression to modify the code is absolute genius. The power of this is not obvious at first to most people. Already I have thought of simple examples. You could write a script which performs some operations, and then deletes itself. You could write a script which counts how many times it has been written.Trivial examples for sure. You could write code, which will modify itself conditionally. The possibilities here are innumerous! Thanks for this!


5. anonymous Fri, 07 Aug 2009 19:48

Thanks! I enjoyed your video tutorial and learned from it as I'm just starting to learn python.

I wanted to find out if you had to import inspect and re to write the self-modifying program, because I don't understand them well yet. I was able to rewrite the program without them:

I used:

f = open(sys.argv[0],'r')

src = f.readlines()

f.close()

instead of:

srcfile = inspect.getsourcefile(sys.modules[__name__])

f = open(srcfile, 'r')

src = f.read()

f.close()

and I used:

for i in range(0,len(src)):

loc = src[i].find(' timestamp =')

if (loc == 0):

src[i] = ' timestamp = ' + '\'' + timestamp + '\''+'\n'

break

newsrc = ''

for i in range(0,len(src)):

newsrc = newsrc + src[i]

instead of:

match = re.search("lastrun = '(.*)'", src)

if match:

src = src[:match.start(1)] + timestamp + src[match.end(1):]

I needed 8 lines to your 3. Then I wrote over the file using newsrc (instead of src).

Maybe in another video you could show advantages and other uses of inspect and re.


4. anonymous Fri, 03 Jul 2009 11:55

Cool!! Thx a lot, I like those things!


3. anonymous Sun, 14 Jun 2009 20:10

well done. interesting.


2. anonymous Sat, 13 Jun 2009 10:43

Very nice!


Lovely little demonstration of some powerful Python modules working in harmony. Learned a few things. It's great to see powerful code created in realtime.

p.s. - you're good to self-publish.


Showmedo is a peer-produced video-tutorials and screencasts site for free and open-source software (FOSS)- with the exception of some club videos, the large majority are free to watch and download.

how to help » about » faq »

Educating the Open-source Community With Showmedo

Although as important as the software it supports, education and documentation are relatively neglected in the Open-source world. Coders love to code, and explaining how best to use or improve the software tends to be deferred or even sidelined.

At Showmedo we believe the community can play a vital role here and also say thanks for the tools and software that make our lives easier. If you have a piece of software you love or a programming langugage you are enthusiastic about, why not make a screencast showing others how to use it? All the stuff you wish you'd been told, the tips, tricks, insights that would have saved you time and frustration.

Screencasting is easier than you think, and we're happy to help you. You can emailus for advice or just use some of the how-to screencasts on the site. This screencasting learning-pathis a good place to start.

Kudos and Thanks for David

Related Videos

Content

Feedback

Showmedo's development is fairly rapid and bugs will inevitably creep in. If you have any problems please drop us a line using the contact address below. Likewise, any suggestions for improvements to the site are gratefully received.

feedback@showmedo.com