python反编译小工具

2,282 阅读1分钟

小知识,大挑战!本文正在参与“程序员必备小知识”创作活动,遇到一个项目,只有pyc文件,看不到源码,怎么从pyc文件反编译为py文件,这时就用到了python包 uncompile6

安装

可通过命令行 pip install uncompile6 或通过pycharm 来安装。 安装成功之后就可以使用了

使用

在命令行输入uncompile6, 会给你返回一些基本用法

image.png

因为项目文件比较多,就写了一个python脚本 主要函数,把pyc文件反编译为py文件

def uncompyle_pyc(filename, newname):
    """
    uncompyle pyc file
    :param filename: pyc file
    :param newname: py file
    :return:
    """
    command = "uncompyle6 -o " + newname + " " + filename
    print(command)
    try:
        os.system(command)
    except Exception as e:
        print("maybe command has Chinese character,notice:command must be English code")
    else:
        print("there is other mistake")

然后遍历工程项目,调用这个函数,把反翻译好的文件也存放在跟这个pyc文件一样的地方。

def detect_walk(dir_path):
    """
    uncompyle all pyc in dirs(include child and parent dirs)
    :param dir_path: root dir
    :return:
    """
    for root, dirs, files in os.walk(dir_path):
        print(root, dirs, files)
        for filename in files:
            if ".pyc" in filename:
                newname = root + spd + filename.split(".")[0] + ".py"
                filename1 = root + spd + filename
                print("%s---->%s" % (filename1, newname))
                uncompyle_pyc(filename1, newname)

这里面还用到了python的os.walk()方法,这个方法是根据自上而下的深度遍历算法,参数是一个目录,把这个参数目录作为根目录进行便利,先读取根目录的文件夹和文件;然后接着从根目录的第一个子目录作为新的根目录读取其文件和文件夹;这样依次遍历,这个函数返回的是个元组(root,dirs,files),以实际例子来说明

image.png