简体   繁体   中英

access python module code

I am trying to access the code that is executed by a module when it is imported.

Visualizing the source or editing it is not the question here. I would like to know where those instructions are stored.

Example

module.py

def func():
    print 'func'

print 'module'

Python console

>>> import module
module
>>> import dis
>>> dis.dis(module)
Disassembly of func:
0 LOAD_CONST               1 ('func')
3 PRINT_ITEM          
4 PRINT_NEWLINE       
5 LOAD_CONST               0 (None)
8 RETURN_VALUE        
>>> dir(module)
['__builtins__', '__doc__', '__file__', '__name__', '__package__', 'func']

Where can I find the <function> object, or the func_code or whatever which stores the print 'module' instruction?

From the documentation:

dis.dis([bytesource])

Disassemble the bytesource object. bytesource can denote either a module, a class, a method, a function, or a code object. For a module, it disassembles all functions.

As module.py is a module, it's disassembling all functions in the module. As the "print 'module'" call is not in a function, it doesn't get disassembled.

EDIT:

To answer the actual question (sorry about that), as the statement is called when you import the module itself, I'm pretty sure that you can solve it as follows (though this is a bit horrible, as solutions go, and there's probably a better way to do it):

class importer():
    def import_module():
        import module
dis.dis(importer)

Which is a slight abuse of how dis works, but hey, it seems to work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM