我这里有一点问题。我有一个 Python 脚本,它调用从 C++ 编译的二进制文件。 Python 脚本有自己的一组输出(标准输出和错误),可以轻松禁用。 C++ 二进制文件也有自己的一组输出(标准输出和错误等);来源可以更改,但我不是原作者。这是一个问题,因为我不希望最终程序中出现 C++ 输出,而且我也不希望未来的用户需要编辑 C++ 源代码。
我想要做的是有一些 Python 方法可以捕获发送到标准输出或错误的 C++ 代码的输出。这可能吗?如果是这样,有人可以指出我正确的方向吗?
谢谢你!!
I have a bit of an issue here. I have a Python script which calls binaries compiled from C++. The Python script has its own set of outputs (to standard out and error), which are easily disable-able. The C++ binaries have their own set of outputs (to standard out and error, among others) as well; the source can be altered, but I am not the original author. This is an issue because I do not want the C++ output in my final program, and I also don't want future users to need to edit the C++ source.
What I'd like to be able to do is have some Python method which will catch the C++ code's output that is sent to standard out or error. Is this possible? If so, could someone point me in the right direction?
Thank you!!
发布评论
评论(2)
一种方法是:
reopen
(来自 C 的stdio
)重定向原始stdout
和stderr
以写入您选择的文件。注意:
reopen
不能直接从 python 中使用,但您应该能够像下面的示例中那样调用它,或者使用任何其他可用的包装器。完成此操作后:
cout
和cerr
的每次写入都会写入输出文件。但是,由于原始描述符是重复的,您仍然可以(参见下面的示例):
sdout.write
打印到原始stdout
/stderr
和stdout.err
stream
参数后使用logging
方法以下代码使用 instant 库,用于测试使用 SWIG 封装到 python 中的真实 C++ 代码,该代码应该与您拥有的库类似:
此示例的输出为:
注意:第一次代码是执行后,您可能会收到
gcc
编译消息(我已删除它们以使示例更清晰)。One way to do this is:
stdout
andstderr
usingos.dup
.stdout
andstderr
usingreopen
(from C'sstdio
) to write to a file of your choice.Note:
reopen
isn't available directly from python, but you should be able to call it as in the example below or using any other wrapper available.After this is done:
cout
andcerr
in C++ will write to the output files.print
statement in python will write to the output files.However, since the original descriptors are duplicated, you can still (see example below):
stdout
/stderr
usingsdout.write
andstdout.err
logging
methods after configuring properly thestream
parameterThe following code uses instant library to test real C++ code that is wrapped into python using SWIG and that should be similar to the library that you have:
The output for this example is:
Note: First time the code is executed, you might get
gcc
compilation messages (I've removed them to make the example clearer).您是否使用
subprocess
来编译C++?如果是这样,您可以设置 stderr 和 stdout 的位置:Are you using
subprocess
to compile the C++? If so, you can set where stderr and stdout go: