0

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

2
Contributors
1
Reply
2
Views
7 Years
Discussion Span
Last Post by dwks
0

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)
This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.