从C 中的Python程序中检索stderr

Retrieve stderr from a python program in a c++ one

本文关键字:检索 stderr 程序 Python 中的      更新时间:2023-10-16

我目前正在尝试使用PSTREAM库(http://pstreams.sourceforge.net/)从我的C 程序中启动用Python编写的文件。我的代码看起来像这样:

QStringList res;
QStringList resErrors;
// run a process and create a streambuf that reads its stdout and stderr
redi::pstream proc(cmd, redi::pstreams::pstdout | redi::pstreams::pstderr);
std::string line;
// read child's stdout
while (std::getline(proc.out(), line))
    res.append(QString::fromStdString(line));
// read child's stderr
while (std::getline(proc.err(), line))
    resErrors.append(QString::fromStdString(line));

通常,我从Pstream构造器中输入的任何命令中正确接收和错误消息。但是,如果我尝试执行一个python文件,以提高追溯,我没有任何输出(在stdout或stderr中)。

例如,此python文件:

#!/usr/bin/env python
test = 5 / 0
print "test"

不会在Stdout中打印"测试",而在Stderr中也不会打印。但是,如果我在终端中执行它,我会正确地得到:

Traceback (most recent call last):
   File "test.py", line 3, in <module>
       test = 5 / 0
   ZeroDivisionError: integer division or modulo by zero

在两种情况下,我都使用了相同的命令:" python test.py"

我想我需要告诉Python将其追溯打印到STDERR?但是,为什么在子过程中没有完成?还是可以是图书馆中的错误?

我想到的另一种可能性是,我读了Stdout和STDERR,而Python还没有时间写。但是我试图在阅读之前添加睡眠功能,没有任何效果。

好吧,通过 @jean-françoisfabre的答案的一部分有效地解决了问题。

我注意到pstreams提供了一种无需阻塞而在管道上阅读的方法,因此我重复使用该代码(在库的文档中找到):

const redi::pstreams::pmode mode = redi::pstreams::pstdout|redi::pstreams::pstderr;
redi::ipstream child(cmd, mode);
char buf[1024];
std::streamsize n;
bool finished[2] = { false, false };
while (!finished[0] || !finished[1])
{
    if (!finished[0])
    {
        while ((n = child.err().readsome(buf, sizeof(buf))) > 0) {
            std::string ret(buf, n);
            resErrors.append(QString::fromStdString(ret));
        }
        if (child.eof())
        {
            finished[0] = true;
            if (!finished[1])
                child.clear();
        }
    }
    if (!finished[1])
    {
        while ((n = child.out().readsome(buf, sizeof(buf))) > 0) {
            std::string out(buf, n);
            res.append(QString::fromStdString(out));
        }
        if (child.eof())
        {
            finished[1] = true;
            if (!finished[0])
                child.clear();
        }
    }
}
res = res.join("").split("n");
resErrors = resErrors.join("").split("n");
res.removeLast();
resErrors.removeLast();

这样,我的QStringLists中都有所有输出!