There is also now tauri-plugin-python to run python code in the tauri backend. This doesn't spawn a new python process on each click but creates a RustPython / PyO3 python interpreter in tauri, which then parses and executes the python code during runtime. The python process doesn't end on each click, so you can also use persistent globals in your python code.
This mostly simplifies python usage in tauri. You don't need to touch any rust code anymore, you just need to have rust&npm installed so you can compile your tauri app. To create a new tauri project using python, you can just use the tauri cli to add the python interpreter.
npm create tauri-app@latest #make sure you use tauri 2
cd tauri-app
npx @tauri-apps/cli add python
# modify src/index.html and add src-tauri/src-python/main.py
npm install
npm run tauri dev
<!-- src/index.html -->
<html>
<head>
<meta charset="UTF-8">
<title>My Tauri App</title>
</head>
<body>
<label for="num1">Enter number 1:</label>
<input type="number" id="num1">
<label for="num2">Enter number 2:</label>
<input type="number" id="num2">
<button id="addBtn">Add Numbers</button>
<div id="result"></div>
<script>
// this should be moved to a main.js file
const tauri = window.__TAURI__;
let num1Input;
let num2Input;
let resultDiv;
async function add_numbers() {
let num1 = parseInt(num1Input.value);
let num2 = parseInt(num2Input.value);
resultDiv.textContent = `Result: ` + await tauri.python.callFunction("add_numbers", [num1, num2]);
}
window.addEventListener("DOMContentLoaded", () => {
num1Input = document.querySelector("#num1");
num2Input = document.querySelector("#num2");
resultDiv = document.querySelector("#result");
document.querySelector("#addBtn").addEventListener("click", (e) => {
add_numbers();
e.preventDefault();
});
});
</script>
</body>
</html>
# src-tauri/src-python/main.py
_tauri_plugin_functions = ["add_numbers"] # allow function(s) to be callable from UI
print("initialized python")
def add_numbers(num1, num2):
result = str(num1 + num2)
print(result)
return "from python: " + result
Disclaimer: I am the author of the python plugin.