0

How can I print out the contents of a Python script?

For example, if I have this (pointless example) script:

my_var = 1 + 1
another_thing = "this is my string"

What line can I add to it, to get the entire contents back?

my_var = 1 + 1
another_thing = "this is my string"

# Magically print out all of the code in this file
print .....
Barmar
  • 741,623
  • 53
  • 500
  • 612
Don P
  • 60,113
  • 114
  • 300
  • 432

1 Answers1

1

Programs that print out their source code are called quines. There are a few good examples here.

The easiest way is to read the script's source file:

print open(__file__).read()

If you can't read from the file, you'll need to wrap all your code in strings. You can then execute the strings and print them separately.

Community
  • 1
  • 1
grc
  • 22,885
  • 5
  • 42
  • 63