Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python script that prints its source

Tags:

python

Is it possible (not necessarly using python introspection) to print the source code of a script?

I want to execute a short python script that also print its source (so I can see which commands are executed).

The script is something like this:

command1()
#command2()
command3()

print some_variable_that_contain_src

The real application is that I want to run a script from IPython with the run -i magic and have as output the source (i.e. the commands executed). In this way I can check which commands are commented at every execution. Moreover, if executed in a Notebook I leave a trace of which commands have been used.

Solution

Using korylprince solution I end up with this one-liner to be put at the beginning of the script:

with open(__file__) as f: print '\n'.join(f.read().split('\n')[1:])

This will print the script source except the first line (that would be only noise). It's also easy to modify the slicing in order to print a different "slice" of the script.

If you want to print the whole file instead, the one-liner simplifies to:

with open(__file__) as f: print f.read()
like image 222
user2304916 Avatar asked Aug 20 '13 02:08

user2304916


2 Answers

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())

like image 152
korylprince Avatar answered Sep 20 '22 05:09

korylprince


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

like image 23
Greg Avatar answered Sep 20 '22 05:09

Greg