簡體   English   中英

如何引導 gnu readline 遠離 stdout

[英]How to direct gnu readline away from stdout

所以我想制作一個程序,通過stdin或交互式輸入接受來自stdin輸入。 getline可以實現getline讀取,但我想為交互式輸入擁有readline所有好的功能。 該程序的目的是通過一種語言操作文本並將結果輸出到標准輸出(類似於 sed 所做的)。 問題是,我無法使用readline執行my_prog > output.txt ,因為無論輸入什么readline的輸出都會進入該文件,我什至看不到它。 目前,我有一個解決方法,我只是使用rl_outstreamreadline的輸出發送到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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM