2010
02.10

Reading an article linked from Barrapunto (a Spanish Slashdot-like site) entitled Reflections on Trusting Trust it came into my attention the paragraph about self-reproducing programs. The author of the article, Ken Thomson says:

More precisely stated, the problem is to write a source program that, when compiled and executed, will produce as output an exact copy of its source. If you have never done this, I urge you to try it on your own. The discovery of how to do it is a revelation that far surpasses any benefit obtained by being told how to do it.

I’ve never tried to code such a thing, so I put my shoulder to the wheel and try this exercise in python. After a few minutes, I got this solution. It’s not the shortest (especially considering it reproduces the shebang and the coding lines), but it works. As Mr. Thomson says, it’s a very interesting exercise. Here’s the code:

Save it as prog1.py, and then execute python prog1.py.
Even better, try python prog1.py > prog2.py and then python prog2.py > prog3.py and so on.

Share