Python编程

把python代码打包成exe文件

将Python代码打包成.exe文件通常需要借助第三方库,最常用的是PyInstaller和 cx_Freeze。这里以PyInstaller为例介绍过程:

安装PyInstaller:打开命令行,先确保已安装pip,如果没有,可以运行

python -m ensurepip --default-pip
然后安装PyInstaller:

pip install pyinstaller

创建spec文件:进入到包含你的Python脚本的目录,运行以下命令,其中your_script.py是你要打包的脚本名:

pyinstaller your_script.py --onefile

这将生成一个名为dist的目录,里面有一个.exe文件。直接从dist目录下运行生成的.exe文件即可。

对于cx_Freeze,流程类似,但配置文件更复杂一些。你需要在setup.py文件中指定要打包的模块和资源。如果你是初学者,PyInstaller更简单易用。
注意:有些库可能在打包过程中无法正常工作,这时你可能需要添加相应的处理,比如处理dll依赖或修改配置。

Debug 1 - UnicodeDecodeError: 'gbk' codec can't decode byte 0xac in position 45: illegal multibyte sequence

在Windows下运行 Python代码时经常遇到如上的提示,这是编码不对导致,有两个点:

一个是cmd控制台的编码,需要切换为Utf-8,在windows的命令行运行以下命令:chcp 65001

二个是python代码里面,加上encoding='utf-8'

with open(filename, encoding='utf-8') as fp:
     self._read(fp, filename)

又如:

with open('ba_config.ini', 'r', encoding='utf-8') as configfile:
        lines = configfile.readlines()

Lesson I - 解rar压缩包的密码

1 下载Python并安装

网址:  注意选对是32 bit还是64 bit

Python Releases for Windows | Python.orgThe official home of the Python Programming Languageicon-default.png?t=O83Ahttps://www.python.org/downloads/windows/ 2 安装unrar

pip install unrar

3 下载unrar的Library

RARLab官方下载库文件  下载地址: http://www.rarlab.com/rar/UnRARDLL.exe 

4 写解密的Python代码

from unrar import rarfile
import os
 
import itertools as its
import time
 
from multiprocessing import Pool
import queue
import threading
 
 
def get_pwd(file_path, output_path, pwd):
    '''
    判断密码是否正确
    :param file_path: 需要破解的文件路径,这里仅对单个文件进行破解
    :param output_path: 解压输出文件路径
    :param pwd: 传入的密码
    :return:
    '''
    try:
        # 传入被解压的文件路径,生成待解压文件对象
        file = rarfile.RarFile(file_path, pwd=pwd)
        # 输出解压后的文件路径
        out_put_file_path = output_path
        # print(file_path,output_path)
        
        file.extractall(output_path)
        # 如果发现文件被解压处理,移除该文件
        # os.remove(out_put_file_path)
        # 说明当前密码有效,并告知
        print('Find password is "{}"'.format(pwd))
 
        return True,pwd
    except Exception as e:
        # 密码不正确
       # print('"{}" is not correct password!'.format(pwd))
        # print(e)
 
        return False,pwd
 
 
def get_password(min_digits, max_digits, words):
    """
    密码生成器
    :param min_digits: 密码最小长度
    :param max_digits: 密码最大长度
    :param words: 密码可能涉及的字符
    :return: 密码生成器
    """
    while min_digits <= max_digits:
        pwds = its.product(words, repeat=min_digits)
        for pwd in pwds:
            yield ''.join(pwd)
        min_digits += 1
 
 
 
if __name__=="__main__":
 
 
    file_path = 'C:\TEMP\python\python.rar'
    output_path = 'C:\TEMP\python'
 
    # 密码范围
    # words = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'  # 涉及到生成密码的参数
    words = '0138'
    pwds = get_password(4, 4, words)
 
    # 开始查找密码
    start = time.time()
 
    # judge = []
    result=queue.Queue(maxsize=10) #队列
    pool = Pool()
    def pool_th():
        while True: ##这里需要创建执行的子进程非常多
            pwd = next(pwds)
            try:
                result.put(pool.apply_async(get_pwd, args=(file_path, output_path, pwd)))
            except:
                break
    def result_th():
        while True:
            #pwd = next(pwds)
            a=result.get().get() #获取子进程返回值
            print(a)
            if a[0]:
                #print(pwd)
                pool.terminate() #结束所有子进程
                break
    '''
    利用多线程,同时运行Pool函数创建执行子进程,以及运行获取子进程返回值函数。
    '''
    t1=threading.Thread(target=pool_th)
    t2=threading.Thread(target=result_th)
    t1.start()
    t2.start()
    t1.join()
    t2.join()
    pool.join()
 
    end = time.time()
    print('程序耗时{}'.format(end - start))

5 运行代码

会出现找不到库的错误:Couldn't find path to unrar library

修改 C:\python\Lib\site-packages\unrar\unrarlib.py

if platform.system() == 'Windows':
    from ctypes.wintypes import HANDLE as WIN_HANDLE
    HANDLE = WIN_HANDLE
    UNRARCALLBACK = ctypes.WINFUNCTYPE(ctypes.c_int, ctypes.c_uint,
                                       ctypes.c_long, ctypes.c_long,
                                       ctypes.c_long)
    lib_path = lib_path or find_library("unrar.dll")
    if lib_path:
        unrarlib = ctypes.WinDLL(lib_path)
    unrarlib = ctypes.WinDLL("C:\\Program Files (x86)\\UnrarDLL\\x64\\unrar.dll")

手工修改unrarlib的路径。

6 如果要把代码迁移到其他机器上,需要准备好Python安装文件( Win7版本- python-3.8.10-amd64.exe;Win10版本- python-3.11.4-amd64.exe) 和unrarDLL.exe

然后安装Python和unrar,使用pip安装unrar模块的时候会报错,因为无法连外网。

此时需要把源机器的 C:\python\Lib\site-packages\unrar 和 C:\python\Lib\site-packages\unrar-0.4.dist-info 两个文件夹考到目标机器里。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值