![](/img/trans.png)
[英]how to output messages to stdout on another thread while reading from stdin with GNU readline without messing up the inputs?
[英]How to direct gnu readline away from stdout
所以我想制作一个程序,通过stdin
或交互式输入接受来自stdin
输入。 getline
可以实现getline
读取,但我想为交互式输入拥有readline
所有好的功能。 该程序的目的是通过一种语言操作文本并将结果输出到标准输出(类似于 sed 所做的)。 问题是,我无法使用readline
执行my_prog > output.txt
,因为无论输入什么readline
的输出都会进入该文件,我什至看不到它。 目前,我有一个解决方法,我只是使用rl_outstream
将readline
的输出发送到stderr
。 这给了我我正在寻找的行为,但是当可能有更直接的解决方案时感觉就像一个黑客。 我正在寻找的一个很好的例子是 python 的作用。
python > output.txt
>>> print 'hello'
>>> exit()
cat output.txt
hello
这是一些代码来演示我在做什么......
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include "readline/readline.h"
int main(int argc, char** argv)
{
char* from_stdin = malloc(512);
char* line = NULL;
rl_outstream = stderr;
if(isatty(STDIN_FILENO)) {
do {
line = readline("");
if(line) {
strcat(from_stdin, line);
strcat(from_stdin, "\n");
} else {
break;
}
} while(1);
} else {
size_t n = 0;
while(getline(&line, &n, stdin) != -1)
strcat(from_stdin, line);
}
puts(from_stdin);
}
已接受解决方案的补丁:
--rl_outstream = stderr;
++FILE* more_hacky = fopen("/dev/tty", "w");
++rl_outstream = more_hacky;
我同意这更hacky。 我可能会按原样保留我的代码,但是如果我选择,这将使 stderr 更“纯”错误。
就其价值而言,CPython确实使用STDERR_FILENO
作为 Readline 的输出文件描述符,如果!isatty(STDOUT_FILENO)
您可以使用strace
等验证这一事实。
没有重定向我们得到
% strace -o strace.out python3 && grep '>>>' strace.out
Python 3.6.7 (default, Oct 22 2018, 11:32:17)
[GCC 8.2.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> ^D
write(1, ">>> ", 4) = 4
并带有重定向
% strace -o strace.out python3 > python.out && grep '>>>' strace.out
Python 3.6.7 (default, Oct 22 2018, 11:32:17)
[GCC 8.2.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> ^D
write(2, ">>> ", 4) = 4
另一种方法是为输出流打开/dev/tty
,但我觉得这会更多,而不是更少,hacky。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.