[英]How to add static(html, css, js, etc) files in pyinstaller to create standalone exe file?
我正在使用QtWebEngineWidgets
、 QtWebChannel
创建 PyQt5 应用程序,它使用 HTML、CSS、JavaScript。
它工作正常,当我们以一般方式运行时,即python main.py
导入 HTML 如下,
current_dir = os.path.dirname(os.path.realpath(__file__))
filename = os.path.join(current_dir, "index.html")
url = QtCore.QUrl.fromLocalFile(filename)
导入 CSS、JavaScript 文件如下,
# in index.html
<link rel="stylesheet" href="styles.css">
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="my_custom.js"></script>
现在,我正在尝试使用pyinstaller
创建一个独立的.exe
文件。
我从这里尝试过但没有成功。
def resource_path(relative_path):
""" Get absolute path to resource, works for dev and for PyInstaller """
try:
# PyInstaller creates a temp folder and stores path in _MEIPASS
base_path = sys._MEIPASS
except Exception:
base_path = os.path.abspath(".")
return os.path.join(base_path, relative_path)
pyinstaller 命令:
pyinstaller --onefile --windowed main.py
我需要在生成的.exe
文件中手动添加静态文件才能按预期工作。 我想将它包含在.exe
文件本身中。 如何得到这个?
根据您的问题,您可以假设您的项目结构如下:
├── index.html
├── jquery.js
├── main.py
├── my_custom.js
└── styles.css
对于您的情况,有两种选择:
import os import sys from PyQt5 import QtCore, QtWidgets, QtWebEngineWidgets def resource_path(relative_path): """ Get absolute path to resource, works for dev and for PyInstaller """ try: # PyInstaller creates a temp folder and stores path in _MEIPASS base_path = sys._MEIPASS except Exception: base_path = os.path.abspath(".") return os.path.join(base_path, relative_path) if __name__ == "__main__": import sys app = QtWidgets.QApplication(sys.argv) view = QtWebEngineWidgets.QWebEngineView() filename = resource_path("index.html") url = QtCore.QUrl.fromLocalFile(filename) view.load(url) view.show() sys.exit(app.exec_())
如果要将外部资源添加到可执行文件,则必须使用“--add-data”选项:
pyinstaller --onefile --windowed --add-data="index.html:." --add-data="jquery.js:." --add-data="my_custom.js:." --add-data="styles.css:." main.py
对于 Windows,将 ":" 更改为 ";"。
使用.qrc
使用此方法,您将使用 pyrcc5 将文件(.html、.css、.js 等)转换为 .py 代码,为此您必须执行以下步骤:
2.1. 在项目文件夹中创建一个名为 resource.qrc 的文件,内容如下:
<RCC> <qresource prefix="/"> <file>index.html</file> <file>jquery.js</file> <file>my_custom.js</file> <file>styles.css</file> </qresource> </RCC>
2.2 使用 pyrcc5 将其转换为 .py:
pyrcc5 resource.qrc -o resource_rc.py
2.3 导入resource_rc.py文件,在main.py文件中使用带有模式“qrc”的url:
import os import sys from PyQt5 import QtCore, QtWidgets, QtWebEngineWidgets import resource_rc if __name__ == "__main__": import sys app = QtWidgets.QApplication(sys.argv) view = QtWebEngineWidgets.QWebEngineView() url = QtCore.QUrl("qrc:/index.html") view.load(url) view.show() sys.exit(app.exec_())
2.4 使用初始命令编译项目
pyinstaller --onefile --windowed main.py
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.