Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -16,4 +16,6 @@ dist
dist-js
!dist-js/*.iife.js
.tokensave
.serena
.serena
# local-only test app, not versioned
/examples/svelte-app/
6 changes: 3 additions & 3 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 2 additions & 2 deletions Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[package]
name = "tauri-plugin-python"
version = "0.4.0"
version = "0.4.1"
authors = [ "Marco Mengelkoch" ]
description = "A tauri 2 plugin to use python code in the backend."
keywords = ["rust", "python", "tauri", "gui"]
Expand All @@ -18,7 +18,7 @@ serde = { version = "1", features = ["derive"] }
thiserror = "2"
async-trait = "0.1"

async_py = { version = "0.4.1", default-features = false }
async_py = { version = "0.4.2", default-features = false }
tokio = { version = "1", features = ["full"] }
serde_json = "1.0.136"
dunce = "1.0.5"
Expand Down
37 changes: 28 additions & 9 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,9 @@ backend and works immediately in `tauri dev`:

```sh
npm run tauri add python
npm install tauri-plugin-python-api
```
`tauri add` only installs the Rust side; the second line adds the JavaScript API.

Create `src-tauri/src-python/main.py`:
```python
Expand Down Expand Up @@ -157,10 +159,16 @@ If `src-python/main.py` doesn't exist, the plugin imports a compiled module name
instead: `main.cpython-313-darwin.so`, `main.pyd`, `main.pyc`, …. This lets you ship your code compiled, e.g.
with [Nuitka](https://nuitka.net/):
```sh
python -m nuitka --module src-tauri/src-python/main.py --output-dir=src-tauri/src-python
# keep the source outside src-python, e.g. in src-tauri/python-src/main.py
src-tauri/pyembed/python/bin/python3 -m venv .nuitka-venv # same Python as the app (after `setup`)
.nuitka-venv/bin/pip install nuitka
.nuitka-venv/bin/python -m nuitka --module src-tauri/python-src/main.py \
--output-dir=src-tauri/src-python --remove-output --no-pyi-file
```
Compiled modules only load into the exact Python version they were built for, so build them with the same
Python version you bundle (see `src-python/.python-version` below). PyO3 backend only.
`main.py` takes precedence, so it must not be in `src-python/` next to the compiled module; everything in
`src-python/` is bundled. Compiled modules only load into the exact Python version they were built for, so
build them with the Python you bundle (see `src-python/.python-version` below). On macOS, run
`tauri-plugin-python-cli sign` afterwards, so they are signed for notarization. PyO3 backend only.

## Example app

Expand All @@ -171,7 +179,7 @@ Javascript in [examples/plain-javascript](https://github.com/marcomq/tauri-plugi

These steps assume that you already have a basic tauri application available. Alternatively, you can immediately start with the application in "example" directory.

- run `npm run tauri add python`
- run `npm run tauri add python` and `npm install tauri-plugin-python-api`
- add `src-tauri/src-python/main.py` and modify it according to your needs, for example add
```python
# src-tauri/src-python/main.py
Expand Down Expand Up @@ -263,13 +271,24 @@ When a Python call fails, the plugin returns the error to the frontend (it is th
try {
await call.greet_python("input value");
} catch (err) {
console.error(err); // contains the Python error message / traceback
console.error(err); // Python error message, with traceback in development builds
}
```

In addition, in **development builds** (`tauri dev`, i.e. any non-release build) the plugin prints the full
error – including the Python traceback – to **stderr**, prefixed with `[tauri-plugin-python]`. Watch the
terminal running `tauri dev` to see it. Release builds do not log, so nothing leaks to end users.
The plugin never shows errors in the UI itself; what the user sees is up to your frontend code.

In **development builds** (`tauri dev`, i.e. any non-release build) the error contains the full Python
traceback, and the plugin also prints it to **stderr**, prefixed with `[tauri-plugin-python]`. Watch the
terminal running `tauri dev` to see it. **Release builds** drop the traceback and log nothing: the frontend
only receives the last line, e.g. `ValueError: invalid input`, so file paths and source lines don't leak to
end users.

For errors that only happen in the release build, start the app with `TAURI_PLUGIN_PYTHON_TRACEBACK=1`.
Errors then contain the traceback and are printed to stderr, as in development builds:

```sh
TAURI_PLUGIN_PYTHON_TRACEBACK=1 ./MyApp.app/Contents/MacOS/MyApp # macOS; on Windows: set the variable, then start the .exe
```

The error message is also prefixed with what the plugin was doing, e.g.
`Error calling Python function 'greet_python': ...` or
Expand Down Expand Up @@ -365,7 +384,7 @@ Notes per platform:
`tauri build`; downloads are cached in `~/.cache/tauri-plugin-python-cli`.
- **macOS:** notarization requires every native file in the app to be signed. Tauri only signs the main binary,
so run `npx tauri-plugin-python-cli sign` (uses `APPLE_SIGNING_IDENTITY`) **before** `tauri build`; it signs
the files in `src-tauri/pyembed`, which tauri then copies into the app.
the native files in `src-tauri/pyembed` and `src-tauri/src-python`, which tauri then copies into the app.
- **Windows:** `python3XX.dll` is placed next to the `.exe`, the rest under `pyembed/`.
- **Linux:** the runtime lands in `/usr/lib/<productName>/pyembed/`.
- `RUSTFLAGS` in the environment replaces the rpaths from `.cargo/config.toml`; `doctor` warns about it.
Expand Down
6 changes: 4 additions & 2 deletions cli/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,8 @@ detects the duplicate `malachite-bigint` versions that break the build;

Notarization rejects unsigned native files anywhere in the app, and tauri only
signs the main binary and frameworks. `sign` signs every Mach-O file in the
bundled Python with `--options runtime --timestamp`, using `--identity` or
bundled Python and in `src-python` (compiled modules, C extensions in a `.venv`)
with `--options runtime --timestamp`, using `--identity` or
`APPLE_SIGNING_IDENTITY` (the same variable `tauri build` uses). It signs the
files in `src-tauri/pyembed`, so run it after `setup` and before `tauri build`.
files in `src-tauri/pyembed` and `src-tauri/src-python`, so run it after `setup`
(and after compiling modules) and before `tauri build`.
6 changes: 4 additions & 2 deletions cli/lib/doctor.js
Original file line number Diff line number Diff line change
Expand Up @@ -218,10 +218,12 @@ function checkBinaries(srcTauri, os, manifest, report) {
const linkage = inspectLinkage(bin, os);
if (!linkage) continue;
const bundled = linkage.rpaths.some((p) => p.includes(`${PYTHON_DIR}/lib`));
// A stale dev build is never shipped, so it must not fail the check.
const fail = profile === "debug" ? report.warn : report.error;
if (!linkage.libpython) report.warn(`${rel}: no libpython dependency found`);
else if (linkage.libpython.startsWith("/")) {
report.error(`${rel}: links the host Python (${linkage.libpython}); rebuild after 'setup'`);
} else if (!bundled) report.error(`${rel}: no rpath to ${PYTHON_DIR}/lib; rebuild after 'setup'`);
fail(`${rel}: links the host Python (${linkage.libpython}); rebuild after 'setup'`);
} else if (!bundled) fail(`${rel}: no rpath to ${PYTHON_DIR}/lib; rebuild after 'setup'`);
else report.ok(`${rel}: links ${linkage.libpython} from the bundled Python`);
}
}
Expand Down
9 changes: 6 additions & 3 deletions cli/lib/sign.js
Original file line number Diff line number Diff line change
Expand Up @@ -49,16 +49,19 @@ export function sign(opts, log = console.log) {
if (process.platform !== "darwin") throw new Error("'sign' is only needed (and possible) on macOS");
const identity = opts.identity ?? process.env.APPLE_SIGNING_IDENTITY;
if (!identity) throw new Error("Pass --identity or set APPLE_SIGNING_IDENTITY (as for tauri build)");
const pythonDir = path.join(findSrcTauri(opts.project), PYTHON_DIR);
const srcTauri = findSrcTauri(opts.project);
const pythonDir = path.join(srcTauri, PYTHON_DIR);
if (!fs.existsSync(pythonDir)) throw new Error(`${PYTHON_DIR} not found. Run 'setup' first`);
// Compiled modules (Nuitka, Cython) and C extensions in a .venv are bundled from src-python.
const dirs = [pythonDir, path.join(srcTauri, "src-python")].filter((d) => fs.existsSync(d));

const targets = [...files(pythonDir)].filter(isMachO);
const targets = dirs.flatMap((d) => [...files(d)]).filter(isMachO);
const args = ["--force", "--sign", identity];
if (identity !== "-") args.push("--timestamp", "--options", "runtime");
if (opts.entitlements) args.push("--entitlements", opts.entitlements);
for (const file of targets) {
const res = spawnSync("codesign", [...args, file], { stdio: "inherit" });
if (res.status !== 0) throw new Error(`codesign failed for ${file}`);
}
log(`Signed ${targets.length} files in ${PYTHON_DIR}`);
log(`Signed ${targets.length} files in ${dirs.map((d) => path.relative(srcTauri, d)).join(", ")}`);
}
2 changes: 1 addition & 1 deletion cli/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "tauri-plugin-python-cli",
"version": "0.4.0",
"version": "0.4.1",
"author": "Marco Mengelkoch",
"description": "Bundle a standalone Python with a tauri-plugin-python app and check the deployment setup.",
"type": "module",
Expand Down
6 changes: 3 additions & 3 deletions docs/deploy-macos.md
Original file line number Diff line number Diff line change
Expand Up @@ -72,9 +72,9 @@ export APPLE_SIGNING_IDENTITY="Developer ID Application: Your Name (TEAMID)"
npx tauri-plugin-python-cli sign
```

This signs every Mach-O file in `src-tauri/pyembed/python` with `--options runtime --timestamp`. Pass
`--entitlements <plist>` if your packages need extra hardened-runtime entitlements. Run `sign` again after each
`setup`.
This signs every Mach-O file in `src-tauri/pyembed/python` and `src-tauri/src-python` (compiled modules, C
extensions in a `.venv`) with `--options runtime --timestamp`. Pass `--entitlements <plist>` if your packages
need extra hardened-runtime entitlements. Run `sign` again after each `setup` and after compiling modules.

## 5. Build

Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "tauri-plugin-python-api",
"version": "0.4.0",
"version": "0.4.1",
"author": "Marco Mengelkoch",
"description": "Javascript package for tauri 2 python plugin.",
"type": "module",
Expand Down
72 changes: 56 additions & 16 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -75,8 +75,11 @@ sys.stderr = _TauriSafeStream(getattr(sys, "stderr", None))

/// Builds the shared [`PyRunner`], applying the default per-call timeout unless
/// the `TAURI_PLUGIN_PYTHON_TIMEOUT_SECS` env var overrides it (`0` = no timeout).
/// Errors include Python tracebacks if [`tracebacks_enabled`].
fn build_runner() -> PyRunner {
let runner = PyRunner::new();
let runner = PyRunner::new().with_tracebacks(tracebacks_enabled(
std::env::var(TRACEBACK_ENV).ok().as_deref(),
));
match call_timeout(
std::env::var("TAURI_PLUGIN_PYTHON_TIMEOUT_SECS")
.ok()
Expand All @@ -87,6 +90,15 @@ fn build_runner() -> PyRunner {
}
}

const TRACEBACK_ENV: &str = "TAURI_PLUGIN_PYTHON_TRACEBACK";

/// Tracebacks are on in debug builds, and in release builds if the
/// `TAURI_PLUGIN_PYTHON_TRACEBACK` env var is `1` or `true`.
fn tracebacks_enabled(env_value: Option<&str>) -> bool {
cfg!(debug_assertions)
|| env_value.is_some_and(|v| matches!(v.trim().to_ascii_lowercase().as_str(), "1" | "true"))
}

/// Resolves the per-call timeout from the raw env var value; `None` disables it.
fn call_timeout(env_value: Option<&str>) -> Option<Duration> {
match env_value.and_then(|v| v.trim().parse::<u64>().ok()) {
Expand All @@ -111,16 +123,18 @@ struct PluginState {
/// Prepends human-readable context to a failing Python operation and, in debug
/// builds (`tauri dev`), prints the full detail - including the Python traceback
/// carried in the underlying error - to stderr so it is visible in the dev
/// console. The original error message is preserved in the returned error, so it
/// also still reaches the frontend. In release builds nothing is logged.
/// console. The full message, traceback included, also reaches the frontend.
/// Release builds log nothing and their errors carry no traceback, unless
/// `TAURI_PLUGIN_PYTHON_TRACEBACK` enables both (see [`tracebacks_enabled`]).
fn py_context<T, E: Into<Error>>(
result: std::result::Result<T, E>,
context: impl FnOnce() -> String,
) -> crate::Result<T> {
result.map_err(|err| {
let msg = format!("{}: {}", context(), err.into());
#[cfg(debug_assertions)]
eprintln!("[tauri-plugin-python] {msg}");
if tracebacks_enabled(std::env::var(TRACEBACK_ENV).ok().as_deref()) {
eprintln!("[tauri-plugin-python] {msg}");
}
Error::String(msg)
})
}
Expand Down Expand Up @@ -290,6 +304,17 @@ enum PythonEntry {
Module { name: String, dir: PathBuf },
}

impl std::fmt::Display for PythonEntry {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
PythonEntry::File(path) => write!(f, "'{}'", path.display()),
PythonEntry::Module { name, dir } => {
write!(f, "compiled module '{name}' from '{}'", dir.display())
}
}
}
}

const ENTRY_MODULE: &str = "main";

/// Prefers `main.py`; otherwise falls back to a compiled `main` module
Expand Down Expand Up @@ -466,8 +491,9 @@ pub fn init_and_register<R: Runtime>(python_functions: Vec<&'static str>) -> Tau
let mut dir = get_resource_dir(app);
let mut entry = find_entry(&dir);
if entry.is_none() {
println!(
"Warning: 'src-tauri/main.py' seems not to be registered in 'tauri.conf.json'"
eprintln!(
"[tauri-plugin-python] Warning: no main.py or compiled 'main' module in '{}'; is 'src-python/' listed in bundle.resources of tauri.conf.json?",
dir.display()
);
// Release builds must not run Python code from wherever they are started.
if cfg!(debug_assertions) {
Expand All @@ -481,9 +507,9 @@ pub fn init_and_register<R: Runtime>(python_functions: Vec<&'static str>) -> Tau
.block_on(async move {
let runner = app.state::<PyRunner>().inner();
init_python(runner, dir.to_path_buf()).await;
run_entry(runner, &entry)
.await
.expect("ERROR: Error running 'src-tauri/main.py'");
if let Err(err) = run_entry(runner, &entry).await {
startup_failed(&format!("Failed to load {entry}"), err);
}
register_python_functions(
app,
python_functions.iter().map(|s| s.to_string()).collect(),
Expand All @@ -505,13 +531,27 @@ pub fn init_and_register<R: Runtime>(python_functions: Vec<&'static str>) -> Tau

async fn register_python_functions<R: Runtime>(app: &AppHandle<R>, python_functions: Vec<String>) {
for function_name in python_functions {
app.register_function(RegisterRequest {
python_function_call: function_name.clone(),
number_of_args: None,
})
.await
.unwrap();
if let Err(err) = app
.register_function(RegisterRequest {
python_function_call: function_name.clone(),
number_of_args: None,
})
.await
{
startup_failed("Failed to register Python functions", err);
}
}
}

/// Aborts plugin initialization with a readable message instead of a `Debug`-formatted error.
fn startup_failed(context: &str, err: impl std::fmt::Display) -> ! {
let mut msg = format!("[tauri-plugin-python] {context}: {err}");
if msg.contains("bad magic number") {
msg.push_str(
"\nHint: the compiled module was built for a different Python version than the one the app runs",
);
}
panic!("{msg}");
}

#[cfg(test)]
Expand Down
13 changes: 5 additions & 8 deletions src/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ use tauri::{
/// It also runs some initial Python code to set up a variable and a function for testing.
async fn mock_app_handle() -> AppHandle<MockRuntime> {
let app = test::mock_app();
let runner = PyRunner::new();
let runner = build_runner();
app.manage(runner);
app.manage(PluginState::default());

Expand Down Expand Up @@ -395,15 +395,12 @@ async fn test_error_message_propagates_from_called_function() {
);
}

// Only the RustPython backend includes a traceback (with line numbers) in the
// error string; PyO3 surfaces just "ExceptionType: message". This pins down that
// running PY_STDIO_GUARD as a *separate* unit beforehand does not shift the line
// numbers reported for subsequently-run user code (the line-3 raise stays line 3).
#[cfg(feature = "rustpython")]
// Pins down that running PY_STDIO_GUARD as a *separate* unit beforehand does not
// shift the line numbers in the traceback of subsequently-run user code. Tracebacks
// are forced on, as `cargo test --release` would otherwise run without them.
#[tokio::test]
async fn test_error_line_number_not_shifted_by_stdio_guard() {
let app = mock_app_handle().await;
let runner = app.state::<PyRunner>().inner();
let runner = PyRunner::new().with_tracebacks(true);
runner.run(PY_STDIO_GUARD).await.unwrap();
let code = "x = 1\ny = 2\nraise ValueError('boom')\n";
let err = runner.run(code).await.unwrap_err().to_string();
Expand Down
16 changes: 16 additions & 0 deletions src/unit_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -340,3 +340,19 @@ mod entry_detection {
assert_eq!(find_entry(&dir.path().join("missing")), None);
}
}

mod traceback {
use super::*;

#[test]
fn env_var_enables_tracebacks() {
assert!(tracebacks_enabled(Some("1")));
assert!(tracebacks_enabled(Some(" TRUE ")));
}

#[test]
fn without_env_var_only_debug_builds_have_tracebacks() {
assert_eq!(tracebacks_enabled(None), cfg!(debug_assertions));
assert_eq!(tracebacks_enabled(Some("0")), cfg!(debug_assertions));
}
}
Loading