1

Recently I have been working on a project that involves generating docx files. Since Rust's docx support is still quite immature, I've decided to use Python's python-docx module via PyO3.

Here's my code so far:

extern crate pyo3;
use pyo3::prelude::*;

(...)

// Initialize some Python
let gil = Python::acquire_gil();
let py = gil.python();
let docx = PyModule::import(py, "docx")?;

let document = docx.Document();

Unfortunately, I'm running into two pretty serious errors.

Error #1:

let docx = PyModule::import(py, "docx")?;
                                   ^ cannot use the `?` operator in a function that returns `std::string::String

Error #2:

let document = docx.Document();
                    ^^^^^^^^ method not found in `&pyo3::prelude::PyModule`

How do I solve these errors?

N.B. Yes, I have made sure that python-docx is installed. It's located in /home/<my username>/.local/lib/python3.8/site-packages

RiverSong
  • 21
  • 3
  • Would the person who downvoted this be so kind as to share why? – RiverSong Jun 01 '21 at 12:04
  • 1
    I am not the person that downvoted, but a quick read of the documentation showed that `PyModule` would be a module implemented in rust (which certainly is not your case), and the [example](https://github.com/PyO3/pyo3#using-python-from-rust) showed the use of `py.import`, where `py` is the current Python interpreter. Some may have deemed that this question may have been asked without sufficient effort in debugging. – metatoaster Jun 01 '21 at 12:07
  • 2
    I am not the downvoter, but I assume the downvoter felt that the question lacked research effort. For example, the first error is very basic Rust and would be resolved by looking into any Rust reference that explains how `?` works. Putting that aside, the easiest way to resolve it is by changing `?` to `.unwrap()`. (`unwrap()` is fine here because you expect `docx` to exist and you want your program to panic if that's not the case.) – user4815162342 Jun 01 '21 at 12:15
  • 2
    As for the second error, it cannot work like that because Rust is a statically typed language, so it cannot just call a `Document` method without it being defined anywhere. Given the dynamic nature of Python, it is likely that you need to access the function name as string, something along the lines of `let document = docx.getattrr("Document").unwrap().call0().unwrap()`. – user4815162342 Jun 01 '21 at 12:15
  • @metatoaster Thank you. I appreciate the feedback. – RiverSong Jun 01 '21 at 12:31

0 Answers0