(A quine is a program that produces its own source as its output, typically to a file.)

import sys
ifile = sys.argv[0]
counter = 0
istream = open(ifile)
source = istream.readlines()
source[2] = 'counter = ' + str(counter + 1) + '\n'
if counter == 0:
    original = str(ifile)
    source.insert(5, 'original = r\'' + str(original) + '\'\n')
ofile = list(original)
ofile.insert(-3, str(counter))
ofile = ''.join(ofile)
ostream = open(ofile, 'w')

It is a naive implementation in that it depends on code that assumes that the new executables are created in and stay in the same directory as the original executable.

Moving the new executable or altering any executable to store the executable in a different directory will break the chain.

The first step to improving the code would be to alter the code so that it can function regardless if it is moved.

After that, I'd like to include code that would automatically execute the new executable. (This is dangerous code that could be considered a form of virus in that it replicates until it consumes all hard disk space. I'll be sure to write a warning against executing the program or remove the code if I am told to cease and desist by moderators.)

My own personal flavour of a quine. It's not the prettiest, I haven't used Python in a while. :)

import sys
before = "#!/usr/bin/python\nimport sys\nbefore = \""
after = "def escape(string, multiline = False):\n\
    string = string.replace(\"\\\\\", \"\\\\\\\\\")\n\
    if not multiline:\n\
        string = string.replace(\"\\n\", \"\\\\n\")\n\
        string = string.replace(\"\\n\", \"\\\\n\\\\\\n\")\n\
    string = string.replace('\"', \"\\\\\\\"\")\n\
    return string\n\
write = sys.stdout.write\n\
write(escape(before) + \"\\\"\\n\")\n\
write('after = \"' + escape(after, True) + \"\\\"\\n\")\n\
def escape(string, multiline = False):
    string = string.replace("\\", "\\\\")
    if not multiline:
        string = string.replace("\n", "\\n")
        string = string.replace("\n", "\\n\\\n")
    string = string.replace('"', "\\\"")
    return string

write = sys.stdout.write

write(escape(before) + "\"\n")

write('after = "' + escape(after, True) + "\"\n")
This article has been dead for over six months. Start a new discussion instead.