Friday, April 10, 2015

A four line Python quine

By Vasudev Ram




Something that happened today made me think of writing a quine, in Python.

A four line Python quine;
how's that for a rhyme?
# Not so good.

A four line Python quine;
Yes, this one is mine.
# Ah, better.

A four line Python quine;
Sure, this too is mine.
# So-so.

A four line Python quine;
Can you stretch that to nine?
# It may not be worth my time.

A four line Python quine;
Hello, sir, rise and shine!

Of course, since the quine prints itself (by definition) when run, I don't need to show the code separately from the output:
$ python quine.py
import sys
with open(sys.argv[0]) as program:
    for line in program:
        sys.stdout.write(line)
Let's check that it works right:
$ python quine.py > pq.py
$ fc /l quine.py pq.py
Comparing files quine.py and PQ.PY
FC: no differences encountered
The quine could be shortened to:
import sys
with open(sys.argv[0]) as p:
    for l in p:
        sys.stdout.write(l)
I'm sure someone can come up with a shorter quine; is it thine? but this was my first time writing one, and I had fun :)

- Enjoy.

- Vasudev Ram - Online Python training and programming

Dancing Bison Enterprises

Signup to hear about new products or services from me.

Posts about Python  Posts about xtopdf

Contact Page

9 comments:

Anonymous said...

import sys
[print(x, end='') for x in open(sys.argv[0])]

Or, oneliner:

[print(x, end='') for x in open(__file__)]

Anonymous said...

That isn't a quine. By definition, a quine takes no input.

Interesting post, anyway.

Unknown said...

A quine cannot take any sort of input.

Reading the source file is cheating.

http://en.m.wikipedia.org/wiki/Quine_(computing)#.22Cheating.22_quines

Holger Joukl said...

Hi Vasudev,
isn't your quine a "cheating quine" as per the definition (http://en.wikipedia.org/wiki/Quine_%28computing%29#.22Cheating.22_quines)
?

Best regards,
Holger

Anonymous said...

print(open(__import__('sys').argv[0]).read())

Vasudev Ram said...

Nice one (rather, two), thanks.

Vasudev Ram said...

To those who commented that it is not a quine - you are correct. I thought the definition at the start of the Wikipedia article meant that a quine should take no explicit input :-(

Thanks for pointing it out.

Anyway, good code golf :)

Vasudev Ram said...

On further thought, if you look at the quite code examples in various examples in the Wikipedia article, many of them include at least part of their own source code within them as strings which they then output.

Vasudev Ram said...

"at the quite code examples in various examples"

should be

"at the code in various examples"

Duh.