10

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:

  1. The inspect import has a getsource 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 to getsource.

  2. I could find the file location of the script file using __file__ or sys.argv[0] and open 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.

agtoever
  • 1,669
  • 16
  • 22

1 Answers1

18

Try:

import inspect
import sys

print inspect.getsource(sys.modules[__name__])

Or even:

import inspect
import sys

lines = inspect.getsourcelines(sys.modules[__name__])[0]

for index, line in enumerate(lines):
    print "{:4d} {}".format(index + 1, line)

The file the code is contained inside is considered to be a Python "module", and sys.modules[__name__] returns a reference to this module.

Edit

Or even, as @ilent2 suggested, like this, without the need of the sys module:

import inspect

print inspect.getsource(inspect.getmodule(inspect.currentframe()))
Will
  • 24,082
  • 14
  • 97
  • 108
  • 1
    Or, with fewer imports but perhaps less readable: `inspect.getsource(inspect.getmodule(inspect.currentframe()))` – ilent2 Dec 28 '15 at 11:03
  • Remark: there's one case where it's buggy, it's the main file loaded in the zip file [linecache cannot get source for the __main__ module with a custom loader · Issue #86291 · python/cpython](https://github.com/python/cpython/issues/86291) – user202729 Dec 24 '22 at 15:32