【问题标题】:Reading all of stdin at program start prevents reading from stdin during the program在程序开始时读取所有标准输入会阻止在程序期间从标准输入读取
【发布时间】:2017-10-16 10:50:06
【问题描述】:

我有一个 golang 程序,可以为 jq 生成一个简单的 repl。我希望能够在程序启动时将来自标准输入的输入读取到一个临时文件中,这样我就可以将 repl 与管道输入一起使用。

cat file.json | jqrepl

但是,当我使用扫描仪或阅读器从标准输入读取时,我到达标准输入的 EOF,然后我不能再接受来自标准输入的主 repl 循环输入。 Readline 立即失败,因为它位于 EOF。

我尝试过推迟 Reader.UnreadByte、关闭扫描仪和大量“seek(0)”,以及 stdin 上的其他原始操作。

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

谢谢!

【问题讨论】:

  • 显示您的代码。
  • 我不认为你能做到这一点 - 当你将文件传送到程序中时,文件内容标准输入。到达 EOF 后,它不会将标准输入返回给终端。您可以将文件路径作为 CLI 参数传递,自己读取文件,然后使用标准输入从终端读取。

标签: bash go pipe stdin read-eval-print-loop


【解决方案1】:

(我想您在 “我不能再接受来自 stdin 的主 repl 循环的输入” 中提到的 stdin 是指到交互式用户输入。)

试试这样:

[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] #

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-10-31
    • 2012-09-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-30
    相关资源
    最近更新 更多