Skip to content

Commit d999aa1

Browse files
committed
add dot notation, make it possible to use import in python
1 parent 322d8dd commit d999aa1

4 files changed

Lines changed: 38 additions & 12 deletions

File tree

guest-js/index.ts

Lines changed: 15 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -18,14 +18,25 @@ export async function runPython(code: string): Promise<string> {
1818
});
1919
}
2020

21-
export async function registerFunction(functionName: string, numberOfArgs?: number): Promise<string> {
21+
/**
22+
* @param {string} pythonFunctionCall - The python function call, can contain one dot
23+
* @param {number} [numberOfArgs] - Number of arguments, used for validation in pythons, use -1 to ignore this value
24+
* @param {string} [jsFunctionName] - Name that is used in javscript: "call.jsFunctionName". Must not contain dots.
25+
*/
26+
export async function registerFunction(pythonFunctionCall: string, numberOfArgs?: number, jsFunctionName?: string): Promise<string> {
27+
if (jsFunctionName === undefined) {
28+
jsFunctionName = pythonFunctionCall;
29+
}
30+
if (numberOfArgs !== undefined && numberOfArgs < 0) {
31+
numberOfArgs = undefined;
32+
}
2233
return await invoke<{ value: string }>('plugin:python|register_function', {
2334
payload: {
24-
functionName,
25-
numberOfArgs,
35+
pythonFunctionCall,
36+
numberOfArgs
2637
},
2738
}).then((r:any) => {
28-
call[functionName] = function (...args: any[]) { return callFunction(functionName, args) };
39+
call[jsFunctionName] = function (...args: any[]) { return callFunction(pythonFunctionCall, args) };
2940
return r.value;
3041
});
3142
}

src/models.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,7 @@ pub enum JsMany {
2626
#[derive(Debug, Deserialize, Serialize)]
2727
#[serde(rename_all = "camelCase")]
2828
pub struct RegisterRequest {
29-
pub function_name: String,
29+
pub python_function_call: String,
3030
pub number_of_args: Option<u8>,
3131
}
3232

src/py_lib.rs

Lines changed: 15 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ use std::{collections::HashMap, ffi::CString, sync::Mutex};
88

99
use lazy_static::lazy_static;
1010
use pyo3::exceptions::PyBaseException;
11-
use pyo3::types::{PyAnyMethods, PyDictMethods};
11+
use pyo3::types::{PyAnyMethods, PyDictMethods, PyList, PyListMethods};
1212
use pyo3::PyErr;
1313
use pyo3::{marker, types::PyDict, Py, PyAny, PyResult};
1414

@@ -26,6 +26,11 @@ pub fn init_python() -> PyResult<()> {
2626
let code = py_main_import::read_at_startup();
2727
let c_code = CString::new(code).expect("error loading python");
2828
marker::Python::with_gil(|py| -> PyResult<()> {
29+
let syspath = py
30+
.import("sys")?
31+
.getattr("path")?
32+
.downcast_into::<PyList>()?;
33+
syspath.insert(0, py_main_import::get_py_path().to_str())?;
2934
let globals = GLOBALS.lock().unwrap().clone_ref(py).into_bound(py);
3035
py.run(&c_code, Some(&globals), None)
3136
})
@@ -39,7 +44,7 @@ pub fn run_python(payload: StringRequest) -> PyResult<()> {
3944
})
4045
}
4146
pub fn register_function(payload: RegisterRequest) -> PyResult<()> {
42-
let fn_name = payload.function_name;
47+
let fn_name = payload.python_function_call;
4348
// TODO, check actual function signature
4449
if INIT_BLOCKED.load(std::sync::atomic::Ordering::Relaxed) {
4550
return Err(pyo3::exceptions::PyException::new_err(
@@ -48,14 +53,20 @@ pub fn register_function(payload: RegisterRequest) -> PyResult<()> {
4853
}
4954
marker::Python::with_gil(|py| -> PyResult<()> {
5055
let globals = GLOBALS.lock().unwrap().clone_ref(py).into_bound(py);
51-
let app = globals.get_item(&fn_name)?;
56+
57+
let fn_dot_split: Vec<&str> = fn_name.split(".").collect();
58+
let app = globals.get_item(&fn_dot_split[0])?;
5259
if app.is_none() {
5360
return Err(pyo3::exceptions::PyException::new_err(format!(
5461
"{} not found",
5562
&fn_name
5663
)));
5764
}
58-
let app = app.unwrap();
65+
let app = if fn_dot_split.len() > 1 {
66+
app.unwrap().getattr(fn_dot_split.get(1).unwrap())?
67+
} else {
68+
app.unwrap()
69+
};
5970
if !app.is_callable() {
6071
return Err(pyo3::exceptions::PyException::new_err(format!(
6172
"{} not a callable function",

src/py_main_import.rs

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2,10 +2,14 @@
22
// © Copyright 2024, by Marco Mengelkoch
33
// Licensed under MIT License, see License file for more details
44
// git clone https://github.com/marcomq/tauri-plugin-python
5-
use std::env;
5+
use std::{env, path::PathBuf};
6+
7+
pub fn get_py_path() -> PathBuf {
8+
env::current_dir().unwrap().join("src-python")
9+
}
610

711
pub fn read_at_startup<'a>() -> String {
8-
let py_file_path = env::current_dir().unwrap().join("src-python/main.py");
12+
let py_file_path = get_py_path().join("main.py");
913
std::fs::read_to_string(py_file_path).unwrap_or_default()
10-
// include_str!(concat!(env!("PWD"), "/src-tauri/src-python/main.py"))
14+
// include_str!(concat!(env!("PWD"), "/src-tauri/src-python/main.py"))
1115
}

0 commit comments

Comments
 (0)