如何在Tauri应用中调用Python脚本实现前后端交互?
Tauri调用Python脚本无响应的修复方案
你代码里的核心问题是Tauri前端不能直接用Node.js的child_process模块,因为Tauri的WebView环境不支持Node.js原生API,得用Tauri官方提供的shell API来调用外部程序。另外你的Python脚本还缺了import sys,加上权限配置没做,这几个点共同导致按钮无响应。
下面是具体修复步骤:
1. 补全Python脚本依赖
你的Python脚本没导入sys模块,运行会直接报错,修改后:
import sys num1 = int(sys.argv[1]) num2 = int(sys.argv[2]) result = num1 + num2 print(str(result))
2. 安装Tauri Shell API依赖
在前端项目目录执行命令安装官方API:
npm install @tauri-apps/api
3. 修改前端代码,替换为Tauri Shell API
把原来依赖Node.js的代码换成Tauri提供的shell模块,修改后的HTML脚本部分:
<script type="module"> import { shell } from '@tauri-apps/api'; const addBtn = document.getElementById('addBtn'); const num1Input = document.getElementById('num1'); const num2Input = document.getElementById('num2'); const resultDiv = document.getElementById('result'); addBtn.addEventListener('click', async () => { const num1 = parseInt(num1Input.value); const num2 = parseInt(num2Input.value); // 先校验输入有效性 if (isNaN(num1) || isNaN(num2)) { resultDiv.textContent = "请输入有效的数字"; return; } try { // 执行Python脚本,注意:如果系统里Python3命令是python3,替换成python3 const output = await shell.execute('python', ['add_numbers.py', num1.toString(), num2.toString()]); if (output.code === 0) { resultDiv.textContent = `Result: ${output.stdout.trim()}`; } else { resultDiv.textContent = `执行错误: ${output.stderr}`; console.error(output.stderr); } } catch (error) { resultDiv.textContent = `调用失败: ${error.message}`; console.error(error); } }); </script>
4. 配置Tauri权限与资源打包
打开src-tauri/tauri.conf.json,做两处配置:
- 添加shell和文件读取权限:
"permissions": { "shell:execute": true, "fs:read": true }
- 确保Python脚本被打包到应用中:
"bundle": { "resources": ["add_numbers.py"] }
5. 调试技巧
如果还是没响应,按下Ctrl+Shift+I打开Tauri开发者工具,查看控制台错误信息,常见问题包括:
- Python命令路径不对(比如系统没把Python加入环境变量)
- 脚本路径错误(确保脚本在项目根目录,或改用绝对路径)
- 权限配置不全导致无法执行命令
最后重启Tauri应用,测试按钮功能即可正常运行。
内容的提问来源于stack exchange,提问作者Faiza Abdella
相关产品推荐
相关产品推荐

