如何从函数创建pyc文件?

时间:2013-07-19 03:20:40

标签: python bytecode pyc

我在用python编码的游戏中,我可以访问所有模块及其功能。

我不想得到一些较大函数的.pyc文件,以便我可以通过dePython或类似的东西。手动阅读这些功能将是一件巨大的痛苦。

假设我有Module.function,我该怎么做才能将该函数转换为.pyc文件?

谢谢!

2 个答案:

答案 0 :(得分:0)

您可以导入模块以自动生成.pyc,或者如果您希望以编程方式执行此操作,请使用py_compile模块:http://docs.python.org/2/library/py_compile.html

答案 1 :(得分:0)

xasm中的函数write_pycfile()可以编写pycfile。它需要一个“ asm”对象,但基本上需要一个Python解释器版本和一个要编写的代码对象列表。它主要使用xdis中的功能。这是一个修改后的版本,主要显示了其工作原理:

import xdis
from xdis import PYTHON3
from xdis.magics import magics
from xdis.marsh import dumps
from struct import pack
import time


def write_pycfile(pyc_file, code_list, version=xdis.PYTHON_VERSION):
    if PYTHON3:
        file_mode = 'wb'
    else:
        file_mode = 'w'

    with open(pyc_file, file_mode) as fp:
        fp.write(magics[version])
        timestamp = int(time.time())
        fp.write(pack('I', timestamp))
        if version > 3.2:
            fp.write(pack('I', 0))
        for co in code_list:
            try:
                co_obj = dumps(co, python_version=str(version))
                if PYTHON3 and version < 3.0:
                    co_obj = str.encode(co_obj)
                    pass

                fp.write(co_obj)
            except:
                pass
            pass
    print("Wrote %s" % pyc_file)

write_pycfile("/tmp/test_pyc.pyc", [write_pycfile.__code__])

现在运行它并反汇编:

$ python /tmp/write-pyc.py 
Wrote /tmp/test_pyc.pyc

$ pydisasm /tmp/test_pyc.pyc
# pydisasm version 4.3.2
# Python bytecode 3.6 (3379)
# Disassembled from Python 3.8.2 (default, Mar 28 2020, 12:46:55) 
# [GCC 7.5.0]
# Timestamp in code: 1587126086 (2020-04-17 08:21:26)
# Method Name:       write_pycfile
# Filename:          /tmp/write-pyc.py
# Argument count:    3
# Kw-only arguments: 0
# Number of locals:  8
# Stack size:        18
# Flags:             0x00000043 (NOFREE | NEWLOCALS | OPTIMIZED)
# First Line:        9
# Constants:
#    0: None
...
# Names:
....    
10:           0 LOAD_GLOBAL               0 (PYTHON3)
              2 POP_JUMP_IF_FALSE        10 (to 10)
...

最后使用uncompyle6进行反编译:

$ uncompyle6 /tmp/test_pyc.pyc
# uncompyle6 version 3.6.5
# Python bytecode 3.6 (3379)
# Decompiled from: Python 3.8.1 (default, Jan 23 2020, 17:02:14) 
# [GCC 7.4.0]
# Embedded file name: /tmp/write-pyc.py
# Compiled at: 2020-04-17 08:21:26
if PYTHON3:
    file_mode = 'wb'
else:
    file_mode = 'w'
with open(pyc_file, file_mode) as (fp):
    fp.write(magics[version])
    timestamp = int(time.time())
    fp.write(pack('I', timestamp))
    if version > 3.2:
        fp.write(pack('I', 0))
    for co in code_list:
        try:
            co_obj = dumps(co, python_version=(str(version)))
            if PYTHON3:
                if version < 3.0:
                    co_obj = str.encode(co_obj)
            fp.write(co_obj)
        except:
            pass

print('Wrote %s' % pyc_file)
# okay decompiling /tmp/test_pyc.pyc