(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')
istream.close()
ofile = list(original)
ofile.insert(-3, str(counter))
ofile = ''.join(ofile)
ostream = open(ofile, 'w')
ostream.writelines(source)
ostream.close()

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. :)

#!/usr/bin/python
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\
    else:\n\
        string = string.replace(\"\\n\", \"\\\\n\\\\\\n\")\n\
    string = string.replace('\"', \"\\\\\\\"\")\n\
    return string\n\
\n\
write = sys.stdout.write\n\
\n\
write(before)\n\
write(escape(before) + \"\\\"\\n\")\n\
\n\
write('after = \"' + escape(after, True) + \"\\\"\\n\")\n\
write(after)"
def escape(string, multiline = False):
    string = string.replace("\\", "\\\\")
    if not multiline:
        string = string.replace("\n", "\\n")
    else:
        string = string.replace("\n", "\\n\\\n")
    string = string.replace('"', "\\\"")
    return string

write = sys.stdout.write

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

write('after = "' + escape(after, True) + "\"\n")
write(after)
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.