Blog by Sumana Harihareswara, Changeset founder
Accidental Quine
Hi, reader. I wrote this in 2013 and it's now more than five years old. So it may be very out of date; the world, and I, have changed a lot since I wrote it! I'm keeping this up for historical archive purposes, but the me of today may 100% disagree with what I said then. I rarely edit posts after publishing them, but if I do, I usually leave a note in italics to mark the edit and the reason. If this post is particularly offensive or breaches someone's privacy, please contact me.
On Friday, while trying to work with standard input (stdin) and command-line arguments (argv), I accidentally wrote an almost-quine (a program that produces its own source code as output). I've removed a few debugging print lines, unused functions, etc. to give you this cleaned-up version:
$ ./script.py testfile.txt #!/usr/bin/python import sys def intakefromfile(): b = sys.argv if len(b) > 0: with open(b[0], 'r') as f: filedata = f.read() return filedata if __name__ == '__main__': print intakefromfile()Explanation: I meant to have script.py grab the first argument to script.py, assume it was a file, and open and print it. However, I failed to actually check the behavior of
sys.argv
ahead of time; turns out that the actual first item in sys.argv
is, in this case, "script.py", not "testfile.txt". You can try this out yourself, and verify that you'll get the same output whether or not you include testfile.txt as an argument. Off-by-one error. I should have had the with open(b[0], 'r')
bit try to open(b[1], 'r')
instead.
Reading a file is cheating in real quine competitions. But I still found this pretty funny.