1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
/*
* rumtk attempts to implement HL7 and medical protocols for interoperability in medicine.
* This toolkit aims to be reliable, simple, performant, and standards compliant.
* Copyright (C) 2025 Luis M. Santos, M.D.
* Copyright (C) 2025 MedicalMasses L.L.C.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
pub mod python_utils {
use std::ffi::{CString, OsStr};
use std::fmt::Debug;
use std::fs::read_to_string;
use std::path::Path;
use crate::core::RUMResult;
use crate::strings::{rumtk_format, RUMString};
use pyo3::prelude::*;
use pyo3::types::{PyList, PyTuple};
pub type RUMPyArgs = Py<PyTuple>;
pub type RUMPyList = Py<PyList>;
pub type RUMPyResultList = Vec<RUMString>;
pub type RUMPyModule = Py<PyModule>;
pub type RUMPyTuple = Py<PyTuple>;
pub type RUMPyFunction = Py<PyAny>;
pub type RUMPyAny = Py<PyAny>;
pub type RUMPython<'py> = Python<'py>;
pub type RUMPyResult<T> = PyResult<T>;
fn string_to_cstring(data: &str) -> RUMResult<CString> {
match CString::new(data) {
Ok(code) => Ok(code),
Err(e) => Err(rumtk_format!(
"Could not cast Python code string to a C string!"
)),
}
}
fn ostring_to_cstring(data: &OsStr) -> RUMResult<CString> {
let data_str = match data.to_str() {
Some(s) => s,
None => return Err(rumtk_format!("Could not cast OsStr to a str!")),
};
match CString::new(data_str) {
Ok(code) => Ok(code),
Err(e) => Err(rumtk_format!(
"Could not cast Python code string to a C string because {:#?}!",
e
)),
}
}
pub fn py_list_to_tuple(py: RUMPython, py_list: &RUMPyList) -> RUMResult<RUMPyTuple> {
match PyTuple::new(py, py_list.bind(py).iter()) {
Ok(py_args) => Ok(py_args.into()),
Err(e) => Err(rumtk_format!(
"Failed to convert arguments from PyList to PyTuple! Reason: {:?}",
e
)),
}
}
///
/// Convert a vector of `T` to a Python List of `T`.
///
/// ## Example
///
/// ```
/// use rumtk_core::strings::rumtk_format;
/// use pyo3::Python;
/// use rumtk_core::scripting::python_utils::{py_buildargs, py_extract_string_vector, py_list_to_tuple};
///
/// let expect: Vec<&str> = vec!["a", "1", "2"];
///
/// Python::attach( |py| {
/// let py_args = py_buildargs(py, &expect).unwrap();
/// let py_obj = py_list_to_tuple(py, &py_args).unwrap();
/// let result = py_extract_string_vector(&py_obj).unwrap();
/// assert_eq!(&result, &expect, "{}", rumtk_format!("Python list does not match the input list!\nGot: {:?}\nExpected: {:?}", &result, &expect));
/// }
/// )
/// ```
///
pub fn py_buildargs<'a, 'py, T>(py: RUMPython<'py>, args: &Vec<T>) -> RUMResult<RUMPyList>
where
T: FromPyObject<'a, 'py> + IntoPyObject<'py> + Debug + Clone,
{
match PyList::new(py, args.clone()) {
Ok(py_args) => Ok(py_args.into()),
Err(e) => Err(
rumtk_format!(
"Failed to convert arguments into a Python Object for transfer to Interpreter! Arguments: {:?} Reason: {:?}",
&args,
e.to_string()
)
)
}
}
///
/// Create empty Python List, which can be used for creating a collection of arguments to pass
/// to script.
///
/// ## Example
///
/// ```
/// use rumtk_core::strings::rumtk_format;
/// use pyo3::Python;
/// use pyo3::types::{PyListMethods, PyAnyMethods};
/// use rumtk_core::scripting::python_utils::{py_new_args, py_push_arg, RUMPyArgs, RUMPyList};
/// use rumtk_core::scripting::python_utils::{py_buildargs, py_extract_string_vector};
///
///
/// Python::attach( |py| {
/// let example_arg_1 = 1;
/// let example_arg_2 = "Hello";
/// let mut py_args: RUMPyList = py_new_args(py);
/// py_push_arg(py, &mut py_args, &example_arg_1.clone()).unwrap();
/// py_push_arg(py, &mut py_args, &example_arg_2.clone()).unwrap();
/// let arg_1: usize = py_args.bind(py).get_item(0).unwrap().extract().unwrap();
/// assert_eq!(&example_arg_1, &arg_1, "{}", rumtk_format!("Python list does not match the input list!\nGot: {:?}\nExpected: {:?}", &arg_1, &example_arg_1));
/// }
/// )
/// ```
///
pub fn py_new_args(py: RUMPython) -> RUMPyList {
PyList::empty(py).unbind()
}
///
/// Push argument of type `T` into instance of Python List. We can then use the list to pass
/// arguments to Python function or method.
///
/// ## Example
///
/// ```
/// use rumtk_core::strings::rumtk_format;
/// use pyo3::Python;
/// use pyo3::types::{PyListMethods, PyAnyMethods};
/// use rumtk_core::scripting::python_utils::{py_new_args, py_push_arg, RUMPyArgs, RUMPyList};
/// use rumtk_core::scripting::python_utils::{py_buildargs, py_extract_string_vector};
///
///
/// Python::attach( |py| {
/// let example_arg_1 = 1;
/// let example_arg_2 = "Hello";
/// let mut py_args: RUMPyList = py_new_args(py);
/// py_push_arg(py, &mut py_args, &example_arg_1.clone()).unwrap();
/// py_push_arg(py, &mut py_args, &example_arg_2.clone()).unwrap();
/// let arg_1: usize = py_args.bind(py).get_item(0).unwrap().extract().unwrap();
/// assert_eq!(&example_arg_1, &arg_1, "{}", rumtk_format!("Python list does not match the input list!\nGot: {:?}\nExpected: {:?}", &arg_1, &example_arg_1));
/// }
/// )
/// ```
///
pub fn py_push_arg<'a, 'py, T>(
py: RUMPython<'py>,
py_args: &mut RUMPyList,
arg: &T,
) -> RUMResult<()>
where
T: FromPyObject<'a, 'py> + IntoPyObject<'py> + Debug + Clone,
{
match py_args.bind(py).append((*arg).clone()) {
Ok(_) => Ok(()),
Err(e) => Err(
rumtk_format!(
"Failed to convert argument into a Python Object for transfer to Interpreter! Argument: {:?} Reason: {:?}",
&arg,
e.to_string()
)
)
}
}
fn string_vector_to_rumstring_vector(list: &Vec<String>) -> RUMPyResultList {
let mut rumstring_vector = Vec::<RUMString>::with_capacity(list.len());
for itm in list {
rumstring_vector.push(RUMString::from(itm));
}
rumstring_vector
}
pub fn py_extract_string_vector(pyargs: &RUMPyArgs) -> RUMResult<RUMPyResultList> {
Python::attach(|py| -> RUMResult<RUMPyResultList> {
let py_list: Vec<String> = match pyargs.extract(py) {
Ok(list) => list,
Err(e) => {
return Err(rumtk_format!(
"Could not extract list from Python args! Reason => {:?}",
e
));
}
};
Ok(string_vector_to_rumstring_vector(&py_list))
})
}
///
/// Extract value returned from functions and modules via a `PyAny` object.
///
/// ## Example Usage
///
/// ### Example W/ RustType
///
/// ```
///use rumtk_core::strings::rumtk_format;
/// use pyo3::Python;
/// use pyo3::types::{PyListMethods, PyAnyMethods, PyString};
/// use rumtk_core::scripting::python_utils::{py_extract_any, py_new_args, py_push_arg, RUMPyArgs, RUMPyList};
/// use rumtk_core::scripting::python_utils::{py_buildargs, py_extract_string_vector};
///
///
/// Python::attach(|py| {
/// let example_arg_1 = "Hello";
/// let py_arg = PyString::new(py, example_arg_1);
/// let arg: String = py_arg.extract().unwrap();
/// let arg_1: String = py_extract_any(py, &py_arg.as_any().clone().unbind()).unwrap();
/// assert_eq!(&example_arg_1, &arg_1, "{}", rumtk_format!("Python conversion failed!\nGot: {:?}\nExpected: {:?}", &arg_1, &example_arg_1));
/// }
/// )
/// ```
///
/// ### Example W/ Custom Type
///
/// ```
///use rumtk_core::strings::rumtk_format;
/// use pyo3::{Python, pyclass, IntoPyObjectExt};
/// use pyo3::types::{PyListMethods, PyAnyMethods, PyString};
/// use rumtk_core::scripting::python_utils::{py_extract_any, py_new_args, py_push_arg, RUMPyAny, RUMPyArgs, RUMPyList};
/// use rumtk_core::scripting::python_utils::{py_buildargs, py_extract_string_vector};
///
/// #[pyclass]
/// #[derive(Clone, Debug, PartialOrd, PartialEq)]
/// struct MyWrapper {
/// text: String
/// }
///
/// Python::attach(|py| {
/// let example_arg_1 = MyWrapper{text: String::from("Hello")};
/// let py_arg: RUMPyAny = example_arg_1.clone().into_py_any(py).unwrap();
/// let arg_1: MyWrapper = py_extract_any(py, &py_arg).unwrap();
/// assert_eq!(&example_arg_1, &arg_1, "{}", rumtk_format!("Python conversion failed!\nGot: {:?}\nExpected: {:?}", &arg_1, &example_arg_1));
/// }
/// )
/// ```
///
pub fn py_extract_any<'py, T>(py: Python<'py>, pyresult: &'py RUMPyAny) -> RUMResult<T>
where
T: FromPyObject<'py, 'py> + Clone,
<T as pyo3::FromPyObject<'py, 'py>>::Error: Debug,
{
match pyresult.extract(py) {
Ok(r) => {
let val = r;
Ok(val)
}
Err(e) => Err(rumtk_format!(
"Could not extract vector from Python result! Reason => {:?}",
e
)),
}
}
///
/// Load a python module from a given file path!
///
/// ## Example Usage
///
/// ```
/// use rumtk_core::strings::rumtk_format;
/// use pyo3::Python;
/// use pyo3::types::PyModule;
/// use rumtk_core::scripting::python_utils::RUMPyModule;
/// use rumtk_core::scripting::python_utils::{py_load};
/// use rumtk_core::strings::RUMString;
/// use uuid::Uuid;
///
/// let expected: &str = "print('Hello World!')\ndef test():\n\treturn 'Hello'";
/// let fpath: RUMString = rumtk_format!("/tmp/{}.py", Uuid::new_v4());
/// std::fs::write(&fpath, expected.as_bytes()).expect("Failure to write test module.");
///
/// Python::attach(|py| {
/// let py_obj: RUMPyModule = py_load(py, &fpath).expect("Failure to load module!");
/// });
/// std::fs::remove_file(&fpath).unwrap()
/// ```
///
pub fn py_load(py: Python, fpath: &str) -> RUMResult<RUMPyModule> {
let pypath = Path::new(fpath);
let pycode = match read_to_string(fpath) {
Ok(code) => string_to_cstring(&code)?,
Err(e) => {
return Err(rumtk_format!(
"Unable to read Python file {}. Is it valid?",
&fpath
));
}
};
let filename = match pypath.file_name() {
Some(name) => ostring_to_cstring(name)?,
None => {
return Err(rumtk_format!("Invalid Python module path {}!", &fpath));
}
};
let modname = match pypath.file_stem() {
Some(name) => ostring_to_cstring(name)?,
None => {
return Err(rumtk_format!("Invalid Python module path {}!", &fpath));
}
};
let pymod = match PyModule::from_code(py, pycode.as_c_str(), &filename, &modname) {
Ok(pymod) => pymod,
Err(e) => {
return Err(rumtk_format!(
"Failed to load Python module {} because of {:#?}!",
&fpath,
e
));
}
};
Ok(pymod.into())
}
///
/// Function for executing a python module's function.
/// If you set the argument `func_name` to an empty string, `py_exec` will do nothing. Allegedly,
/// the module executed upon import.
///
/// It is recommended you have a function to call from the module!!!
///
/// # Examples
///
/// ## Executing Function Within Module
///
/// ```
/// use rumtk_core::strings::rumtk_format;
/// use pyo3::{Python, IntoPyObjectExt};
/// use pyo3::types::PyModule;
/// use rumtk_core::scripting::python_utils::{RUMPyAny, RUMPyArgs, RUMPyModule, RUMPyList};
/// use rumtk_core::scripting::python_utils::{py_load, py_exec_module, py_buildargs, py_list_to_tuple};
/// use uuid::Uuid;
/// use rumtk_core::strings::RUMString;
///
/// let expected: &str = "print('Hello World!')\ndef test():\n\treturn 'Hello'";
/// let fpath: RUMString = rumtk_format!("/tmp/{}.py", Uuid::new_v4());
/// std::fs::write(&fpath, expected.as_bytes()).expect("Failure to write test module.");
///
/// let expect: Vec<&str> = vec![];
///
/// Python::attach( |py| {
/// let py_obj: RUMPyModule = py_load(py, &fpath).expect("Failure to load module!");
/// let args: RUMPyList = py_buildargs(py, &expect).unwrap();
///
/// let result = py_exec_module(py, &py_obj, "test", &args).expect("Failed to extract result!");
/// });
///
/// std::fs::remove_file(&fpath).unwrap()
///```
///
/// ## Executing Module
///
/// ```
/// use rumtk_core::strings::rumtk_format;
/// use pyo3::{Python, IntoPyObjectExt};
/// use pyo3::types::PyModule;
/// use rumtk_core::scripting::python_utils::{RUMPyAny, RUMPyArgs, RUMPyModule, RUMPyList};
/// use rumtk_core::scripting::python_utils::{py_load, py_exec_module, py_new_args};
/// use uuid::Uuid;
/// use rumtk_core::strings::RUMString;
///
/// let expected: &str = "print('Hello World!')\ndef test():\n\treturn 'Hello'";
/// let fpath: RUMString = rumtk_format!("/tmp/{}.py", Uuid::new_v4());
/// std::fs::write(&fpath, expected.as_bytes()).expect("Failure to write test module.");
///
/// let expect: Vec<&str> = vec![];
///
/// Python::attach( |py| {
/// let py_obj: RUMPyModule = py_load(py, &fpath).expect("Failure to load module!");
/// let args: RUMPyList = py_new_args(py);
///
/// let result = py_exec_module(py, &py_obj, "", &args).expect("Failed to extract result!");
/// });
///
/// std::fs::remove_file(&fpath).unwrap()
///```
///
pub fn py_exec_module(
py: Python,
pymod: &RUMPyModule,
func_name: &str,
args: &RUMPyList,
) -> RUMResult<RUMPyAny> {
if !func_name.is_empty() {
let pyfunc: RUMPyFunction = match pymod.getattr(py, func_name) {
Ok(f) => f,
Err(e) => {
return Err(rumtk_format!(
"No function named {} found in module! Error: {:#?}",
&func_name,
e
));
}
};
match pyfunc.call1(py, py_list_to_tuple(py, args)?) {
Ok(r) => Ok(r),
Err(e) => Err(rumtk_format!(
"An error occurred executing Python function {}. Error: {}",
&func_name,
e
)),
}
} else {
Ok(py_new_args(py).into_any())
}
}
///
/// Runs a closure that follows the signature `|py: RUMPython| -> R {}`.
/// Remember, the type of the `py` token needs to be explicitly added or there will be a type
/// inference error from Rust about lifetimes when in fact the closure has no lifetime issues.
/// See example below.
///
/// ## Examples
///
/// ### Running A Function With Arguments and Result
///
/// ```
/// use std::fs::write;
/// use pyo3::Python;
/// use uuid::Uuid;
/// use rumtk_core::core::RUMResult;
/// use rumtk_core::scripting::python_utils::{py_extract_any, py_new_args, py_push_arg, py_exec, py_exec_module, py_load, RUMPython};
/// use rumtk_core::scripting::python_utils::{RUMPyModule};
///
/// fn test_module_exec() -> f64 {
/// let module_fname = format!("{}_module.py", Uuid::new_v4());
/// let module_contents = "def test(a,b):\n\treturn a+b";
/// write(&module_fname, module_contents).expect("Failed to write file!");
///
/// let closure = |py: RUMPython| -> RUMResult<f64> {
/// let a = 5;
/// let b = 5.0;
///
/// let mut args = py_new_args(py);
/// py_push_arg(py, &mut args, &a);
/// py_push_arg(py, &mut args, &b);
///
/// let pymod: RUMPyModule = py_load(py, &module_fname).expect("Failure to load module!");
///
/// let result = py_exec_module(py, &pymod, "test", &args).unwrap();
/// let val: f64 = py_extract_any(py, &result).unwrap();
///
/// Ok(val)
/// };
///
/// let result = py_exec(closure);
/// std::fs::remove_file(&module_fname).unwrap();
///
/// result.unwrap()
/// }
///
/// let result = test_module_exec();
///
/// assert_eq!(10.0, result, "Bad value returned from Python snippet!")
///
/// ```
///
pub fn py_exec<F, R>(closure: F) -> R
where
F: FnOnce(RUMPython) -> R,
{
Python::attach(|py: RUMPython| -> R { closure(py) })
}
}
pub mod python_macros {
///
/// Load a Python module and execute contents.
///
/// ## Example
///
/// ### Running the Module
///
/// ```
/// use std::fs::write;
/// use pyo3::Python;
/// use uuid::Uuid;
/// use rumtk_core::core::RUMResult;
/// use rumtk_core::rumtk_python_exec_module;
///
/// fn test_module_exec() {
/// let module_fname = format!("{}_module.py", Uuid::new_v4());
/// let module_contents = "print(\"Hello World!\")";
/// write(&module_fname, module_contents).expect("Failed to write file!");
///
/// let result = Python::attach(|py| -> RUMResult<()> {
/// rumtk_python_exec_module!(py, &module_fname);
/// Ok(())
/// });
/// std::fs::remove_file(&module_fname).unwrap();
/// }
///
/// test_module_exec()
///
/// ```
///
/// ### Running A Function
///
/// ```
/// use std::fs::write;
/// use pyo3::Python;
/// use uuid::Uuid;
/// use rumtk_core::core::RUMResult;
/// use rumtk_core::rumtk_python_exec_module;
///
/// fn test_module_exec() {
/// let module_fname = format!("{}_module.py", Uuid::new_v4());
/// let module_contents = "def test():\n\tprint(\"Hello World!\")";
/// write(&module_fname, module_contents).expect("Failed to write file!");
///
/// let result = Python::attach(|py| -> RUMResult<()> {
/// rumtk_python_exec_module!(py, &module_fname, "test");
/// Ok(())
/// });
/// std::fs::remove_file(&module_fname).unwrap();
/// }
///
/// test_module_exec()
///
/// ```
///
/// ### Running A Function With Result
///
/// ```
/// use std::fs::write;
/// use pyo3::Python;
/// use uuid::Uuid;
/// use rumtk_core::core::RUMResult;
/// use rumtk_core::scripting::python_utils::py_extract_any;
/// use rumtk_core::rumtk_python_exec_module;
///
/// fn test_module_exec() -> usize {
/// let module_fname = format!("{}_module.py", Uuid::new_v4());
/// let module_contents = "def test():\n\treturn 5+5";
/// write(&module_fname, module_contents).expect("Failed to write file!");
///
/// let result = Python::attach(|py| -> RUMResult<usize> {
/// let result = rumtk_python_exec_module!(py, &module_fname, "test");
/// let val: usize = py_extract_any(py, &result)?;
/// Ok(val)
/// });
/// std::fs::remove_file(&module_fname).unwrap();
///
/// result.unwrap()
/// }
///
/// let result = test_module_exec();
///
/// assert_eq!(10, result, "Bad value returned from Python snippet!")
///
/// ```
///
/// ### Running A Function With Arguments and Result
///
/// ```
/// use std::fs::write;
/// use pyo3::Python;
/// use uuid::Uuid;
/// use rumtk_core::core::RUMResult;
/// use rumtk_core::scripting::python_utils::{py_extract_any, py_new_args, py_push_arg};
/// use rumtk_core::rumtk_python_exec_module;
///
/// fn test_module_exec() -> f64 {
/// let a = 5;
/// let b = 5.0;
///
/// let module_fname = format!("{}_module.py", Uuid::new_v4());
/// let module_contents = "def test(a,b):\n\treturn a+b";
/// write(&module_fname, module_contents).expect("Failed to write file!");
///
/// let result = Python::attach(|py| -> RUMResult<f64> {
/// let mut args = py_new_args(py);
/// py_push_arg(py, &mut args, &a);
/// py_push_arg(py, &mut args, &b);
///
/// let result = rumtk_python_exec_module!(py, &module_fname, "test", &args);
/// let val: f64 = py_extract_any(py, &result)?;
/// Ok(val)
/// });
/// std::fs::remove_file(&module_fname).unwrap();
///
/// result.unwrap()
/// }
///
/// let result = test_module_exec();
///
/// assert_eq!(10.0, result, "Bad value returned from Python snippet!")
///
/// ```
///
#[macro_export]
macro_rules! rumtk_python_exec_module {
( $py:expr, $mod_path:expr) => {{
use pyo3::types::PyModule;
use pyo3::{IntoPyObjectExt, Python};
use $crate::scripting::python_utils::{
py_buildargs, py_exec_module, py_list_to_tuple, py_load, py_new_args,
};
use $crate::scripting::python_utils::{RUMPyAny, RUMPyArgs, RUMPyList, RUMPyModule};
use $crate::strings::RUMString;
// Load module
let pymod: RUMPyModule = py_load($py, $mod_path)?;
// Empty args
let args = py_new_args($py);
// Let's execute against arguments
py_exec_module($py, &pymod, "", &args)?
}};
( $py:expr, $mod_path:expr, $func_name:expr ) => {{
use pyo3::types::PyModule;
use pyo3::{IntoPyObjectExt, Python};
use $crate::scripting::python_utils::{
py_buildargs, py_exec_module, py_list_to_tuple, py_load, py_new_args,
};
use $crate::scripting::python_utils::{RUMPyAny, RUMPyArgs, RUMPyList, RUMPyModule};
use $crate::strings::RUMString;
// Load module
let pymod: RUMPyModule = py_load($py, $mod_path)?;
// Empty args
let args = py_new_args($py);
// Let's execute against arguments
py_exec_module($py, &pymod, $func_name, &args)?
}};
( $py:expr, $mod_path:expr, $func_name:expr, $args:expr ) => {{
use pyo3::types::PyModule;
use pyo3::{IntoPyObjectExt, Python};
use $crate::scripting::python_utils::{
py_buildargs, py_exec_module, py_list_to_tuple, py_load,
};
use $crate::scripting::python_utils::{RUMPyAny, RUMPyArgs, RUMPyList, RUMPyModule};
use $crate::strings::RUMString;
// Load module
let pymod: RUMPyModule = py_load($py, $mod_path)?;
// Let's execute against arguments
py_exec_module($py, &pymod, $func_name, $args)?
}};
}
///
/// Execute the contents of a closure passed to this macro. This macro is an alias for
/// [rumtk_core::scripting::python_utils::py_exec].
///
/// See the blurp about that function to learn more!
///
/// ## Closure Format
///
/// ### Without Return
///
/// ```text
/// |py: RUMPython| {
/// rumtk_python_exec_module!(py, "module/path");
/// };
/// ```
///
/// ### With Return
///
/// ```text
/// |py: RUMPython| -> usize {
/// let result = rumtk_python_exec_module!(py, "module/path", "my_python_function");
/// let val: usize = py_extract_any(py, &result)?;
/// val
/// };
/// ```
///
/// ## Example
///
/// ### Running the Module
///
/// ```
/// use std::fs::write;
/// use pyo3::Python;
/// use uuid::Uuid;
/// use rumtk_core::scripting::python_utils::RUMPython;
/// use rumtk_core::core::RUMResult;
/// use rumtk_core::{rumtk_python_exec_module, rumtk_python_exec};
///
/// fn test_module_exec() {
/// let module_fname = format!("{}_module.py", Uuid::new_v4());
/// let module_contents = "print(\"Hello World!\")";
/// write(&module_fname, module_contents).expect("Failed to write file!");
///
/// let closure = |py: RUMPython| -> RUMResult<()> {
/// rumtk_python_exec_module!(py, &module_fname);
/// Ok(())
/// };
///
/// let result = rumtk_python_exec!(closure);
/// std::fs::remove_file(&module_fname).unwrap();
/// }
///
/// test_module_exec()
///
/// ```
///
/// ### Running A Function
///
/// ```
/// use std::fs::write;
/// use pyo3::Python;
/// use uuid::Uuid;
/// use rumtk_core::core::RUMResult;
/// use rumtk_core::scripting::python_utils::RUMPython;
/// use rumtk_core::{rumtk_python_exec_module, rumtk_python_exec};
///
/// fn test_module_exec() {
/// let module_fname = format!("{}_module.py", Uuid::new_v4());
/// let module_contents = "def test():\n\tprint(\"Hello World!\")";
/// write(&module_fname, module_contents).expect("Failed to write file!");
///
/// let closure = |py: RUMPython| -> RUMResult<()> {
/// rumtk_python_exec_module!(py, &module_fname, "test");
/// Ok(())
/// };
///
/// let result = rumtk_python_exec!(closure);
/// std::fs::remove_file(&module_fname).unwrap();
///
/// }
///
/// test_module_exec()
///
/// ```
///
/// ### Running A Function With Result
///
/// ```
/// use std::fs::write;
/// use pyo3::Python;
/// use uuid::Uuid;
/// use rumtk_core::core::RUMResult;
/// use rumtk_core::scripting::python_utils::{py_extract_any, RUMPython};
/// use rumtk_core::{rumtk_python_exec_module, rumtk_python_exec};
///
/// fn test_module_exec() -> usize {
/// let module_fname = format!("{}_module.py", Uuid::new_v4());
/// let module_contents = "def test():\n\treturn 5+5";
/// write(&module_fname, module_contents).expect("Failed to write file!");
///
/// let closure = |py: RUMPython| -> RUMResult<usize> {
/// let result = rumtk_python_exec_module!(py, &module_fname, "test");
/// let val: usize = py_extract_any(py, &result)?;
/// Ok(val)
/// };
///
/// let result = rumtk_python_exec!(closure);
/// std::fs::remove_file(&module_fname).unwrap();
///
/// result.unwrap()
/// }
///
/// let result = test_module_exec();
///
/// assert_eq!(10, result, "Bad value returned from Python snippet!")
///
/// ```
///
/// ### Running A Function With Arguments and Result
///
/// ```
/// use std::fs::write;
/// use pyo3::Python;
/// use uuid::Uuid;
/// use rumtk_core::core::RUMResult;
/// use rumtk_core::scripting::python_utils::{py_extract_any, py_new_args, py_push_arg, RUMPython};
/// use rumtk_core::{rumtk_python_exec, rumtk_python_exec_module};
///
/// fn test_module_exec() -> f64 {
/// let module_fname = format!("{}_module.py", Uuid::new_v4());
/// let module_contents = "def test(a,b):\n\treturn a+b";
/// write(&module_fname, module_contents).expect("Failed to write file!");
///
/// let closure = |py: RUMPython| -> RUMResult<f64> {
/// let a = 5;
/// let b = 5.0;
///
/// let mut args = py_new_args(py);
/// py_push_arg(py, &mut args, &a);
/// py_push_arg(py, &mut args, &b);
///
/// let result = rumtk_python_exec_module!(py, &module_fname, "test", &args);
/// let val: f64 = py_extract_any(py, &result)?;
/// Ok(val)
/// };
///
/// let result = rumtk_python_exec!(closure);
/// std::fs::remove_file(&module_fname).unwrap();
///
/// result.unwrap()
/// }
///
/// let result = test_module_exec();
///
/// assert_eq!(10.0, result, "Bad value returned from Python snippet!")
///
/// ```
///
#[macro_export]
macro_rules! rumtk_python_exec {
( $closure:expr ) => {{
use $crate::scripting::python_utils::py_exec;
py_exec($closure)
}};
}
}