views:

43

answers:

2

Is it possible to construct human readable source for loaded modules if you have access to sys.modules?

People tell me you cannot, but I'm sure it is possible in Python.

+4  A: 

You can disassemble a Python-coded module using the dis module of the standard library: that produces definitely human readable source, just not Python source, but rather bytecode source. Putting eggs back together starting from the omelette is a tad harder.

There used to be a decompiler for Python 2.3 (see here) but I don't know if anybody's been maintaining it over the last several years, which suggests there isn't much interest in this task in the open source community. If you disagree, you could fork that project, making your own project with the goal of decompiling 2.7 (or whatever Python release you crave to decompile for), and attract others enthusiastic about this task -- if you can find them, that is.

Alex Martelli
... and even if you get a working decompiler (in the sense that the result *works*), it propably won't produce readable/maintanable source code, at least not reliably. +1 anyway.
delnan
Possible yes, easy - not at all.
Eloff
A: 

Generally, the source code will be available in the file system, in places that can be easily discovered from sys.modules.

for name, mod in sys.modules.items():
    try:
        fname = mod.__file__
    except AttributeError:
        continue
    if fname.endswith(".pyc"):
        fname = fname[:-1]
    try:
        fcode = open(fname)
    except IOError:
        continue
    code = fcode.read()
    # .. do something with name and code
Ned Batchelder