mxivideo/docs/PYTHON_EMBEDDED_SOLUTION.md

134 lines
2.6 KiB
Markdown
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# Python嵌入式分发方案备选
## 方案概述
如果PyInstaller sidecar方案遇到问题可以考虑直接将Python嵌入式版本打包到应用中。
## 实现步骤
### 1. 下载Python嵌入式版本
```bash
# Windows
wget https://www.python.org/ftp/python/3.11.0/python-3.11.0-embed-amd64.zip
# 解压到 src-tauri/python-embed/
```
### 2. 安装依赖到嵌入式Python
```python
# scripts/setup_embedded_python.py
import subprocess
import sys
from pathlib import Path
def setup_embedded_python():
embed_dir = Path("src-tauri/python-embed")
python_exe = embed_dir / "python.exe"
# 安装pip
subprocess.run([
str(python_exe), "-m", "ensurepip", "--default-pip"
])
# 安装依赖
subprocess.run([
str(python_exe), "-m", "pip", "install",
"requests", "Pillow", "opencv-python-headless"
])
# 复制python_core模块
import shutil
shutil.copytree("python_core", embed_dir / "python_core")
if __name__ == "__main__":
setup_embedded_python()
```
### 3. 修改Tauri配置
```json
{
"bundle": {
"resources": [
"python-embed/**"
]
}
}
```
### 4. 修改Rust执行器
```rust
fn get_embedded_python_path() -> Option<PathBuf> {
let exe_dir = std::env::current_exe().ok()?
.parent()?;
let python_exe = if cfg!(target_os = "windows") {
exe_dir.join("python-embed/python.exe")
} else {
exe_dir.join("python-embed/bin/python3")
};
if python_exe.exists() {
Some(python_exe)
} else {
None
}
}
async fn execute_with_embedded_python(
module: &str,
action: &str,
params: Option<&str>,
) -> Result<String, String> {
let python_exe = get_embedded_python_path()
.ok_or("Embedded Python not found")?;
let mut cmd = Command::new(python_exe);
cmd.args(&[
"-m", &format!("python_core.{}", module),
"--action", action
]);
if let Some(p) = params {
cmd.args(&["--params", p]);
}
// 执行命令...
}
```
## 优缺点对比
### PyInstaller Sidecar方案
**优点**
- 单文件分发
- 启动速度快
- 内存占用相对较小
**缺点**
- 构建复杂
- 调试困难
- 可能遇到兼容性问题
### 嵌入式Python方案
**优点**
- 构建简单
- 调试容易
- 兼容性好
**缺点**
- 分发包较大
- 启动速度较慢
- 安全性较低
## 推荐方案
1. **首选**PyInstaller Sidecar方案
2. **备选**嵌入式Python方案
3. **开发**系统Python方案
根据项目需求和技术栈选择最适合的方案。