Reading all of stdin at program start prevents reading from stdin during the program

huangapple go评论106阅读模式
英文:

Reading all of stdin at program start prevents reading from stdin during the program

问题

我有一个使用golang编写的程序,用于创建一个简单的jq repl。我希望能够在程序启动时从标准输入读取输入并保存到临时文件中,这样我就可以使用管道输入来操作repl。

cat file.json | jqrepl

然而,当我从标准输入读取时,无论是使用扫描器还是读取器,我都会达到标准输入的EOF,然后我就无法再接受来自标准输入的输入用于主repl循环。因为已经到达EOF,所以Readline立即失败。

我尝试过使用Reader.UnreadByte进行延迟操作,关闭扫描器,以及在标准输入上进行多种"seek(0)"和其他原始操作。

有没有办法重置标准输入,使其可以再次读取?理想情况下,我希望读取直到EOF,将其保存到临时文件中,然后进入repl模式。

谢谢!

英文:

I have a golang program that makes a simple repl for jq. I'd like to be able to read input from stdin at program start into a temporary file, so I can use the repl with piped input.

cat file.json | jqrepl

However, when I read from stdin, either using a scanner or a reader, I reach the EOF for stdin, and then I can no longer accept input from stdin for the main repl loop. Readline fails immediately because it's at EOF.

I've tried deferring a Reader.UnreadByte, Closing the scanner, and a multitude of "seek(0)", and other raw operations on stdin.

Is there a way to reset the stdin so that it can be read from again? Ideally I would read until EOF, save that to a temporary file, and then enter the repl mode.

Thanks!

答案1

得分: 1

(我假设你提到的“stdin”是指“我不能再接受主要repl循环的标准输入”中的交互式用户输入。)

尝试像这样:

<!-- language: none -->

[步骤 101] # cat foo.sh
while read line; do
    printf '&gt; %s\n' "$line"
done

# 关闭 stdin
exec 0&lt;&amp;-
# 重新打开 stdin 到 /dev/tty
exec 0&lt; /dev/tty

read -p '输入一些内容:' v
printf '你输入的是:%s\n' "$v"
[步骤 102] # printf '%s\n' foo bar | bash ./foo.sh
&gt; foo
&gt; bar
输入一些内容:hello world
你输入的是:hello world
[步骤 103] #
英文:

(I suppose the stdin you mentioned as in "I can no longer accept input from stdin for the main repl loop" is referring to the interactive user input.)

Try like this:

<!-- language: none -->

[STEP 101] # cat foo.sh
while read line; do
    printf &#39;&gt; %s\n&#39; &quot;$line&quot;
done

# close stdin
exec 0&lt;&amp;-
# reopen stdin to /dev/tty
exec 0&lt; /dev/tty

read -p &#39;Input something: &#39; v
printf &#39;You inputted: %s\n&#39; &quot;$v&quot;
[STEP 102] # printf &#39;%s\n&#39; foo bar | bash ./foo.sh
&gt; foo
&gt; bar
Input something: hello world
You inputted: hello world
[STEP 103] #

huangapple
  • 本文由 发表于 2017年5月17日 14:19:01
  • 转载请务必保留本文链接:https://go.coder-hub.com/44016980.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定