简体   繁体   English

访问python模块代码

[英]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 module.py

def func():
    print 'func'

print 'module'

Python console Python控制台

>>> 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? 在哪里可以找到<function>对象,func_code或存储print'module print 'module'指令的任何内容?

From the documentation: 从文档中:

dis.dis([bytesource]) dis.dis([bytesource])

Disassemble the bytesource object. 反汇编bytesource对象。 bytesource can denote either a module, a class, a method, a function, or a code object. bytesource可以表示模块,类,方法,函数或代码对象。 For a module, it disassembles all functions. 对于模块,它将分解所有功能。

As module.py is a module, it's disassembling all functions in the module. 由于module.py是一个模块,因此它正在分解模块中的所有功能。 As the "print 'module'" call is not in a function, it doesn't get disassembled. 由于“ print'module'”调用不在函数中,因此不会被反汇编。

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. 稍微滥用了dis的工作原理,但嘿,它似乎有效。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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