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

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.