fix: 修复 Python 进程启动失败问题

🔧 **Python 进程启动修复**:

1. **问题诊断**:
   - 用户日志显示 Python 进程启动后无输出
   - Rust 代码假设 Windows 有 'python' 命令
   - 实际系统可能只有 'python3' 或 'py' 命令

2. **多 Python 命令支持**:
   - Windows: 尝试 ['python', 'python3', 'py']
   - Linux/macOS: 尝试 ['python3', 'python']
   - 自动检测可用的 Python 解释器
   - 详细的错误日志和重试机制

3. **增强错误处理**:
   - 每个 Python 命令尝试都有详细日志
   - 失败时显示具体错误原因
   - 最终失败时提供完整的错误信息

4. **Python 脚本调试增强**:
   - 添加启动时的详细信息输出
   - 显示 Python 版本、工作目录、参数
   - 模块导入错误的详细诊断
   - 关键路径和环境信息输出

5. **环境测试函数同步修复**:
   - test_ai_video_environment 使用相同的多命令策略
   - 更好的错误报告和诊断信息

 **修复效果**:
- 支持多种 Python 命令 ✓
- 详细的启动和错误日志 ✓
- 自动环境检测和适配 ✓
- 更好的问题诊断能力 ✓

现在应该能够在不同的 Python 环境中正常启动!
This commit is contained in:
root 2025-07-10 14:21:01 +08:00
parent a56400b4d2
commit 47899ba5f5
2 changed files with 84 additions and 32 deletions

View File

@ -14,6 +14,15 @@ from typing import Dict, Any, List, Optional, Callable
import sys
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
# Add startup logging
print("=== AI Video Generator Starting ===")
print(f"Python version: {sys.version}")
print(f"Working directory: {os.getcwd()}")
print(f"Script path: {__file__}")
print(f"Arguments: {sys.argv}")
print("=====================================")
sys.stdout.flush()
try:
from config import settings
from utils import setup_logger
@ -29,11 +38,22 @@ try:
from .cloud_storage import CloudStorage
from .api_client import APIClient
from .jsonrpc import create_response_handler, create_progress_reporter, JSONRPCError
except ImportError:
# Fallback for when running as script
from cloud_storage import CloudStorage
from api_client import APIClient
from jsonrpc import create_response_handler, create_progress_reporter, JSONRPCError
print("Successfully imported local modules")
except ImportError as e:
print(f"Import error with relative imports: {e}")
try:
# Fallback for when running as script
from cloud_storage import CloudStorage
from api_client import APIClient
from jsonrpc import create_response_handler, create_progress_reporter, JSONRPCError
print("Successfully imported modules with direct imports")
except ImportError as e2:
print(f"CRITICAL ERROR: Failed to import required modules: {e2}")
print("Python path:", sys.path)
print("Current directory contents:", os.listdir("."))
print("Module directory contents:", os.listdir(os.path.dirname(__file__)))
sys.stdout.flush()
sys.exit(1)
logger = setup_logger(__name__)

View File

@ -37,22 +37,41 @@ async fn execute_python_command(_app: tauri::AppHandle, args: &[String]) -> Resu
println!("Working directory: {:?}", project_root);
// Try python3 first, then python (for Windows compatibility)
let python_cmd = if cfg!(target_os = "windows") {
"python"
// Try multiple Python commands in order of preference
let python_commands = if cfg!(target_os = "windows") {
vec!["python", "python3", "py"]
} else {
"python3"
vec!["python3", "python"]
};
let mut cmd = Command::new(python_cmd);
cmd.current_dir(&project_root);
cmd.args(args);
cmd.stdout(std::process::Stdio::piped());
cmd.stderr(std::process::Stdio::piped());
let mut child = None;
let mut last_error = String::new();
println!("Starting Python process...");
let mut child = cmd.spawn()
.map_err(|e| format!("Failed to start Python process: {}", e))?;
for python_cmd in python_commands {
println!("Trying Python command: {}", python_cmd);
let mut cmd = Command::new(python_cmd);
cmd.current_dir(&project_root);
cmd.args(args);
cmd.stdout(std::process::Stdio::piped());
cmd.stderr(std::process::Stdio::piped());
match cmd.spawn() {
Ok(process) => {
println!("Successfully started Python process with: {}", python_cmd);
child = Some(process);
break;
}
Err(e) => {
last_error = format!("Failed to start {} process: {}", python_cmd, e);
println!("{}", last_error);
continue;
}
}
}
let mut child = child.ok_or_else(|| {
format!("Failed to start Python process with any command. Last error: {}", last_error)
})?;
let stdout = child.stdout.take().unwrap();
let stderr = child.stderr.take().unwrap();
@ -196,24 +215,37 @@ pub async fn test_ai_video_environment(_app: tauri::AppHandle) -> Result<String,
println!("Testing from project root: {:?}", project_root);
// Try python3 first, then python (for Windows compatibility)
let python_cmd = if cfg!(target_os = "windows") {
"python"
// Try multiple Python commands in order of preference
let python_commands = if cfg!(target_os = "windows") {
vec!["python", "python3", "py"]
} else {
"python3"
vec!["python3", "python"]
};
let output = Command::new(python_cmd)
.current_dir(&project_root)
.args(&["-c", "import sys; print(f'Python {sys.version}'); import requests; print('requests OK'); import PIL; print('PIL OK')"])
.output()
.map_err(|e| format!("Failed to execute Python test: {}", e))?;
for python_cmd in python_commands {
println!("Testing Python command: {}", python_cmd);
let output = Command::new(python_cmd)
.current_dir(&project_root)
.args(&["-c", "import sys; print(f'Python {sys.version}'); import requests; print('requests OK'); import PIL; print('PIL OK')"])
.output();
if output.status.success() {
let stdout = String::from_utf8_lossy(&output.stdout);
Ok(format!("Environment test passed:\n{}", stdout))
} else {
let stderr = String::from_utf8_lossy(&output.stderr);
Err(format!("Environment test failed:\n{}", stderr))
match output {
Ok(output) => {
if output.status.success() {
let stdout = String::from_utf8_lossy(&output.stdout);
return Ok(format!("Environment test passed with {}:\n{}", python_cmd, stdout));
} else {
let stderr = String::from_utf8_lossy(&output.stderr);
println!("Python {} test failed: {}", python_cmd, stderr);
continue;
}
}
Err(e) => {
println!("Failed to execute Python {}: {}", python_cmd, e);
continue;
}
}
}
Err("Failed to find a working Python installation".to_string())
}