从python解释器恢复.pyc文件

时间:2014-07-28 17:34:43

标签: python

因为我是一个白痴,我删除了一些python文件并且无法支持它们。在此之前,我打开了python解释器(即运行python),然后使用命令import myfile.py

编辑:我实际上使用了命令import myfile,显然情况更糟。

有没有办法可以从我打开的python解释器会话中恢复.pyc(或更好的.py,但这似乎是不可能的)文件?

2 个答案:

答案 0 :(得分:4)

字节码反编译器uncompyle2可以将Python 2.x类,方法,函数和代码反编译为源代码(注意:通过Reassembling Python bytecode to the original code?)。

这对于功能来说效果很好:

from StringIO import StringIO
from uncompyle2 import uncompyle
from inspect import *

def decompile_function(f, indent=''):
    s = StringIO()
    uncompyle(2.7, f.func_code, s)
    return '%sdef %s%s:\n%s    %s' % (
        indent,
        f.func_name,
        inspect.formatargspec(*inspect.getargspec(f)),
        indent,
        ('\n    ' + indent).join(''.join(s.buflist).split('\n')))

不幸的是,因为类已经执行,它将无法恢复其结构;你需要单独反编译这些方法并希望这就足够了:

def decompile_class(c):
    return 'class %s(%s):\n' % (
        c.__name__,
        ','.join(b.__module__ + '.' + b.__name__ for b in c.__bases__)) + \
        '\n'.join(decompile_function(m.im_func, '    ')
                  for n, m in inspect.getmembers(c) if inspect.ismethod(m))

完整解决方案:

def decompile_module(mod):
    return '\n\n'.join(decompile_function(m) if isfunction(m) else
        decompile_class(m) if isclass(m) else
        '# UNKNOWN: ' + repr((n, m))
        for n, m in inspect.getmembers(mod) if inspect.getmodule(m) is mod)

答案 1 :(得分:1)

inspect.getsource支持转储模块,因此您可以简单地

import inspect
inspect.getsource(myfile)

由于这似乎不起作用,您至少应该能够使用

获取反汇编(" .pyc)代码
import dis
dis.dis(myfile)
相关问题