Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Wrap a Python io object in an ostream #1477

Open
Quincunx271 opened this issue Aug 1, 2018 · 2 comments
Open

Wrap a Python io object in an ostream #1477

Quincunx271 opened this issue Aug 1, 2018 · 2 comments

Comments

@Quincunx271
Copy link
Contributor

I claim that it would be worthwhile to allow Python io objects to be wrapped into std::ostreams. Currently, one has to use scoped_ostream_redirect like so:

m.def("foo", [](pybind11::object io) {
    std::ostringstream out;

    pybind11::scoped_ostream_redirect redirect{out, file};

    // rest of code, using `out` as the std::ostream&
});

However, std::ostream can be constructed by a std::streambuf. scoped_ostream_redirect uses a streambuf implementation. Thus, it's possible to directly create a std::ostream from the object:

pybind11::detail::pythonbuf buffer{io};
std::ostream out{&buffer};

What I'm leading up to is this (currently doesn't work):

m.def("foo", [](std::ostream& out) {
    // using `out` as before
});

Which could be used in Python as if it were a regular Python io object:

import io
out = io.StringIO()
m.foo(out)
print(out.getvalue())
@YannickJadoul
Copy link
Collaborator

Could be possible. It would be interesting to see how easy it would be to add to pybind11.
If you (or anyone else) feel(s) like submitting a PR, please do!

@adam-urbanczyk
Copy link

adam-urbanczyk commented Nov 24, 2020

This gist seems to do what you need https://gist.github.com/asford/544323a5da7dddad2c9174490eb5ed06 (NB: I did not test it, nor did I write it). @asford maybe you'd be interested in contributing your gist to pybind11?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants