英文:
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 '> %s\n' "$line"
done
# 关闭 stdin
exec 0<&-
# 重新打开 stdin 到 /dev/tty
exec 0< /dev/tty
read -p '输入一些内容:' v
printf '你输入的是:%s\n' "$v"
[步骤 102] # printf '%s\n' foo bar | bash ./foo.sh
> foo
> 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 '> %s\n' "$line"
done
# close stdin
exec 0<&-
# reopen stdin to /dev/tty
exec 0< /dev/tty
read -p 'Input something: ' v
printf 'You inputted: %s\n' "$v"
[STEP 102] # printf '%s\n' foo bar | bash ./foo.sh
> foo
> bar
Input something: hello world
You inputted: hello world
[STEP 103] #
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论