2

i wanted to know how to use python script with tauri app, i tried a few things but failed i try to take an input from the user using html tag then want to pass it to python and then after the python code does the adding wanted to display the result back in the html page, i got confused how to communicate the two of them(python and javascript) i saved my python script in the same directory as the html but when i click the button there is not response,

this is my python script

    num1 = int(sys.argv[1])
    num2 = int(sys.argv[2])
    result = num1 + num2
    print(str(result))

and this is the html part

<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>
    const { spawn } = require('child_process');

    const addBtn = document.getElementById('addBtn');
    const num1Input = document.getElementById('num1');
    const num2Input = document.getElementById('num2');
    const resultDiv = document.getElementById('result');

    addBtn.addEventListener('click', () => {
      const num1 = parseInt(num1Input.value);
      const num2 = parseInt(num2Input.value);

      const python = spawn('python', ['add_numbers.py', num1.toString(), num2.toString()]);

      python.stdout.on('data', data => {
        const result = data.toString().trim();
        resultDiv.textContent = `Result: ${result}`;
      });

      python.stderr.on('data', error => {
        console.error(error.toString());
      });
    });
  </script>
</body>
</html>

i saved my python script in the same directory as the html but when i click the button there is not response,

2 Answers2

1

I am building an app utilising Tauri, Python and React. You can spawn the python instance as a "sidecar" as they're called in the Tauri platform.

Tauri offers several ways to communicate between tauri-sidecar & tauri-react frontend.

You may find documentation on embedding binaries as a sidecar to the Tauri app here; https://tauri.app/v1/guides/building/sidecar/

Once you build your python script into a standalone executable using PyInstaller, you can place it in your project folder, and then initiate that as a sidecar executable.

Once you initiate the sidecar; at the very simplest, you can listen to the stdout of the python executable, from the tauri app.

    let (mut rx, mut child) = Command::new_sidecar("pythonexecutablename")
    .expect("failed to create `pythonexecutablename` binary command")
    .spawn()
    .expect("Failed to spawn sidecar");

tauri::async_runtime::spawn(async move {
    let main_window = app.get_window("main").unwrap();
    while let Some(event) = rx.recv().await {
        if let CommandEvent::Stdout(line) = event {
            println!("Output from sidecar command: {}", line);
            if line.contains("MESSAGE:STARTED") {
                main_window
                    .emit("sidecar-ready", Some(()))
                    .expect("failed to emit event");
            }
            main_window
                .emit("message", Some(format!("'{}'", line)))
                .expect("failed to emit event");
            child.write("message from Rust\n".as_bytes()).unwrap();
        }
    }
});

In a similar fashion, you can also communicate between the React app and the Tauri app as well.

import { emit, listen } from "@tauri-apps/api/event";
import { invoke } from "@tauri-apps/api/tauri";
invoke("is_app_ready").then((message) => {
  console.log("RN - tauri app responded : ", message);
  if (message === true) {
    // Call listenUp when sidecar is ready
    initiateListening();
  } else {
    const handler = listen("sidecar-ready", (event) => {
      initiateListening();
    });
  }
});

I personally wouldn't depend heavily on the specialised communication interface provided by the Tauri API, because you never know when you may switch your UI layer, or have another user interface for the backend, so once I complete the initialisation and initial handshake, I start an SSE endpoint (server-side sent events) directly to the python backend. Then listen to that from the react app.

Max Abrahamsson
  • 1,460
  • 3
  • 17
  • 35
0

Disclaimer

What you are asking for, can be achieved, but I will assume that you are a beginner dev, since you want to use python alongside HTML.

With that in mind, let me tell you that this is a horrible idea.
Yes, it isn't impossible, but it has no real benefit to it.

You should be using JavaScript or TypeScript in the frontend part of a Tauri app.

Answer

If you kept reading, that means you are still interested in using python.

There are two ways of going about this.

  • The first way is to use a library like PyScript that runs python natively on the browser.
  • The second way has two options.
    • Bundling the python interpreter with your app, and spawn a child process from the Rust backend using tauri's Command API (what you were already attempting to do from the frontend)

Comment

I can't stress enough how bad of an idea this is, python was not made for the web, and you already have a great language as your backend...Rust.

When you find yourself in a situation where nothing works the way you want it to, you should think if what you want to do actually makes sense.

Arjix
  • 146
  • 9
  • 1
    rust is good, the reason i wanted python was for its huge library and pakages for machine learning ai and deep learning , i know it is slow but still for its simplicity i need, and please dont understmate like that, i know it has no use to make tauri work like that but untill it become famous to find lots of tutorial on it still its confusing – Faiza Abdella Jun 18 '23 at 18:47