[英]Redirecting output from gnome-terminal using QProcess in C++
我正在尝试为gui生成一个子进程,该子进程将生成一个终端。 我希望此终端产生的数据(stdout和stderr)显示在出现的窗口以及设置的日志文件中。 当我直接在外壳中键入命令时,它可以按预期工作,但是当作为启动命令提供给QProcess时,它实际上不会向文件中写入任何内容。
例如:如果用户未安装二进制文件,则应将其写到bin.log,该命令未找到。 我将生成的QProcess的环境设置为与正在运行的父进程相同(以便它可以查找bash和其他内容),并在调用QProcess.start()方法之前设置了工作目录。 我写了一个测试用例,内容如下:
gnome-terminal --title 'Sub-Terminal' -e 'bash -c "foo [args to foo] |& tee foo.log"'
在Qt中,我执行以下操作:
QProcess *child = new QProcess(this);
QString cmd = "gnome-terminal --title 'Sub-Terminal' -e 'bash -c \"foo [args to foo] |& tee foo.log\"'";
child->setProcessEnvironment(<process environment I have created before>);
child->setWorkingDirectory(<current working dir>);
child->start(cmd);
...
它生成终端,但不将任何数据写入foo.log。 我也尝试了以下方法:
QProcess *child = new QProcess(this);
QString prog = "gnome-terminal"
QStringList args;
args << "-x" << "bash" << "foo" << "[foo's arguments]" << "|&" << "tee" << "foo.log";
// set the process env and working dir
child->start(prog, args);
有人对如何解决这个问题有任何建议吗? 我已经尝试过使用QProcess.setStandardErrorFile(foo.log)和QProcess.setStandardOutputFile(foo.log)重定向stdout和stderr,但是看来这将从gnome-terminal本身重定向stdout(这不是什么)。
您必须将要在终端中执行的整个命令作为QProcess
单个参数提供给"-e"
,以及将要在bash中执行的命令作为bash的单个参数提供:
args << "-e" << "bash -c 'foo [args to foo] |& tee foo.log'";
这基本上执行
bash -c 'foo [args to foo] |& tee foo.log'
在终端中,它自己执行
foo [args to foo] |& tee foo.log
在bash内。
您的猜测是正确的,即无法从gnome-terminal
进程读取输出。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.