In python, how to capture the stdout from a c++ shared library to a variable

前端 未结 7 1927
别那么骄傲
别那么骄傲 2020-11-30 04:52

For some other reasons, the c++ shared library I used outputs some texts to standard output. In python, I want to capture the output and save to a variable.

7条回答
  •  盖世英雄少女心
    2020-11-30 05:29

    It's basically untenable to capture the stdout from library code because that depends on your code running in an environment where a.) you're on a shell and b.) there's no other content going to your stdout. While you can probably make something work under these constraints, if you intend to deploy this code in any sense at all there is just no way to reasonably guarantee consistent good behavior. In fact, it's pretty questionable that this library code prints to stdout in a way that can't be controlled anyways.

    So that's what you can't do. What you can do is to wrap any printing calls to this library inside something you can execute in a subprocess. Using Python's subprocess.check_output you can then get the stdout from that subprocess back in your program. Slow, messy, kinda grody all around, but on the other hand the library you're using prints useful information to stdout and doesn't return it so...

提交回复
热议问题