This a small utility library to facilitate working with python file-like with rust.
```rust use pyo3_file::PyFileLikeObject; use pyo3::types::PyString;
use pyo3::prelude::*; use pyo3::wrap_pyfunction; use std::io::Read;
/// Represents either a path File
or a file-like object FileLike
enum FileOrFileLike { File(String), FileLike(PyFileLikeObject), }
impl FileOrFileLike {
pub fn frompyobject(pathorfilelike: PyObject) -> PyResult
// is a path
if let Ok(string_ref) = path_or_file_like.cast_as::<PyString>(py) {
return Ok(FileOrFileLike::File(
string_ref.to_string_lossy().to_string(),
));
}
// is a file-like
match PyFileLikeObject::new(path_or_file_like) {
Ok(f) => Ok(FileOrFileLike::FileLike(f)),
Err(e) => Err(e),
}
}
}
fn acceptspathorfilelike(pathorfilelike: PyObject) -> PyResult
let mut buffer = vec![0; 4096];
Ok(f.read(&mut buffer)?)
}
},
Err(e) => Err(e)
}
}
fn examplemodule(py: Python, m: &PyModule) -> PyResult<()> { m.addwrapped(wrappyfunction!(acceptspathorfilelike))?;
Ok(())
}
```
and use from python:
```python from examplemodule import acceptspathorfile_like
def main(): # works acceptspathorfilelike("./some_file.txt")
# also works
f = open('./some_file.txt')
accepts_path_or_file_like(f)
```