1

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.

2 Answers 2

4

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.

Sign up to request clarification or add additional context in comments.

2 Comments

... 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.
Possible yes, easy - not at all.
0

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

Comments

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.