Showing posts with label Python-quine. Show all posts
Showing posts with label Python-quine. Show all posts

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