I want to get the current script as a string in a variable in Python.
I found two sub-optimal ways, but I hope there is a better solution. I found:
The
inspect
import has agetsource
method, but that only returns the code of one function (or class or whatever), but not the entire script. I can't find a way to pass the object of the entire script togetsource
.I could find the file location of the script file using
__file__
orsys.argv[0]
andopen
it to read. But this seems too indirect to me.
So: is there a (better) way to access the entire script as a string?
If relevant: I'd prefer a Python 2.7 solution above a 3.x.