Python script that prints its source

As long as you're not doing anything crazy with packages, put this at the top of your script

with open(__file__) as f:
    print f.read()

Which will read in the current file and print it out.

For python 3 make sure to use instead print(f.read())


For the most simple answer:

import my_module

print open(my_module.__file__).read()

I also tried using the inspect package.

import inspect

import my_module

source_list = inspect.getsourcelines(my_module)

Will give you a list of strings with the source code defined in it

for line in source_list[0]:
    print line

Will print out the entire source code in a readable manner

Tags:

Python