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.

7
  • 1
    What are you actually trying to achieve with this? Commented Dec 28, 2015 at 10:50
  • Possible dup here. Commented Dec 28, 2015 at 10:51
  • Not quite the same it seems, and the answers provided don't really show how to access the script's own code, but rather, the code of other scripts. Commented Dec 28, 2015 at 11:00
  • @jonrsharpe it's for a codegolf puzzle. Commented Dec 28, 2015 at 11:32
  • 1
    @jonrsharpe: I had the same question. In my case, I have a data processing script that dumps the results to a file, and I'd like to record exactly /how/ it does it together with the results. Commented Dec 2, 2017 at 8:11

1 Answer 1

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()))
Sign up to request clarification or add additional context in comments.

2 Comments

Or, with fewer imports but perhaps less readable: inspect.getsource(inspect.getmodule(inspect.currentframe()))
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

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.