pyinstaller打包成exe可执行文件

1. 安装

pip install pyinstaller

注意项目开发时,最好先创建一个虚拟环境。

2.基本命令和参数


# 1.1依赖的文件,打包进exe
pyinstaller --hidden-import your_module your_script.py
pyinstaller --hidden-import utils -w main.py
-w 来让程序运行时不显示黑窗口
#1.2 添加依赖
pyinstaller --add-data "dependency_folder;dependency_folder" your_script.py
# 1.3 打包资源文件
pyinstaller
--add-data "resources/file1.txt;resources" --add-data "resources/file2.txt;resources" your_script.py
# 打包成单个exe
pyinstaller -F main.py -i favicon.ico

 

3.打包

方式1:打包成文件夹

 打包完成后:

 

方式2:打包成单个exe文件

# 依赖文件也打包如exe
pyinstaller --hidden-import utils -F run.py

 1.单个依赖文件非同级目录,打包进exe

 2.或将整个依赖包打进exe

 3. 资源文件如何再exe执行目录中能访问到,需要在执行文件运行目录创建资源文件目录和文件

 

本案例涉及到的代码

import sys
import time
import os
from playwright.sync_api import sync_playwright
print(os.getcwd())
with open("../1.txt", 'w', encoding="utf-8") as f:
    f.write(os.getcwd())
ex_script_dir= os.getcwd()
# browser_executable_path = r"D:\tools\chromium-win64\chrome-win\chrome.exe"
browser_executable_path = os.path.join(os.path.join(ex_script_dir,"chrome-win"),"chrome.exe")
def get_baidu():
    p = sync_playwright().start()
    browser = p.chromium.launch(executable_path=browser_executable_path, headless=False)
    page = browser.new_page()
    url = 'https://www.baidu.com'
    page.goto(url)
    time.sleep(3)
    browser.close()
if __name__ == '__main__':
    get_baidu()
tools.py
from utils.tools import get_baidu

get_baidu()

with open("./resources/2.txt","r",encoding="utf-8") as f:
    html = f.read()
    print(html)
run.py

 

posted @ 2023-08-22 20:35  冰底熊  阅读(146)  评论(0编辑  收藏  举报