从C 中的Python程序中检索stderr
Retrieve stderr from a python program in a c++ one
我目前正在尝试使用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中都有所有输出!
相关文章:
- 如何将stdout重定向到stderr
- 使用VerQueryValue检索应用程序的文件描述
- 是否可以从格式字符串中检索"width"
- 使用 pqxx 将 std::vector 存储在 postgresql 中,并从数据库中检索它
- 如何在QByteArray中放置和检索位字段而不会感到痛苦?
- 如何在Qt中从数据库中检索二进制数据?
- 如何从C++代码中检索 QML 的文本字段中的文本?
- 从 opencv c++ 中的矢量中检索固定的帧数
- 如何在不等待检索的情况下获取C++中的内存位置?
- 如何在 QTreeWidget 中检索特定项目的 mimeData?
- C++从字符串中检索几行
- 在数据库中插入和检索矩阵
- 两个垫子的 OpenCV 数据是相同的,但使用 Mat::at 检索时的值已损坏
- 使用 const char* 键映射 C++ 检索空值
- 打印从SQLite3数据库检索的数据C++与命令行中相同的方式
- 如何检索指向在单独线程上运行的函数的移动指针?
- 如何检索 Steamwork SDK 的当前版本
- 通过 host() 从 af::array 检索数据会导致错误的数据
- 无法从类中检索值
- 从C 中的Python程序中检索stderr