Communicating with python

Hi, sorry, this must be an age-old question, but all my searches regarding Rust/Python communication seem to be building modules you can call from python, not the other way around.

Let's say I have some pretty rust data-structure that encapsulates all the data needed to then be formatted into a Word Doc, and say the rust ecosystem for creating word docs is a little under developed still. I want to ship my data somehow to python and build my docx from there - where the ecosystem is much more developed.

The way I was thinking was to use serde to serialize my data - use std::Command to call a python script that is expecting to read the data from stdin via a pipe, python deserializes and then creates the docx for me.

Is there a better or more standard/idiomatic way to do this?

The excellent pyo3 crate allows calling Python from Rust: Calling Python from Rust - PyO3 user guide

In addition, if you are willing to use nightly Rust, there is the incredibly convenient inline-python crate.

1 Like

ah right, i thought py03 was precisely about building executable modules in python!

I like my idea of serde + Command + pipe because compile times are already a bit too large for my tastes, so i don't want to pull in new libraries for the fringe parts of my codebase, and the FFI boundary is going to be very infrequently modified, so I'm happy to duplicate code on the python side, and then I still get a pure python environment to write my python code in.

What do you think?

1 Like

PyO3 contains APIs for both directions (calling Python from Rust and calling Rust from Python).

1 Like

If you don't need complex interaction and only need simple data transportation and performance is not a big issue, that should be OK, I think.

1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.