创建一个不向标准输出写入内容的用户提示。

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

Create a user prompt that does not write to stdout

问题

在bash中,有一个名为read的内置命令,它有一个-p选项。例如:

read -p "请输入一个值:" value
echo "${value}"

如果像这样执行该文件$ ./bashfile > result.txt

你将得到一个包含$value\n而不是请输入一个值:$value\n的文件。

在Go语言中,你可以做类似的事情。下面是一段代码:

fmt.Print("请输入一个值:")
reader := bufio.NewReader(os.Stdin)
value, _ := reader.ReadString('\n')
fmt.Println(value)

如果你使用$ ./goexecutable > result.txt运行它

result.txt的内容将会是请输入一个值:value\n

在Go语言中是否有类似于bash中read -p<PROMPT>字符串,它可以在命令行中打印,但不会输出到标准输出(stdout)?

英文:

In bash, there is a builtin called read which has the -p switch. For example:

read -p &quot;Please enter a value: &quot; value
echo &quot;${value}&quot;

If this file is then executed like $ ./bashfile &gt; result.txt

You will end up with a file containing $value\n, but NOT Please enter a value: $value\n

In go, you can do something similar. Here's a section of code:

fmt.Print(&quot;Please enter a value: &quot;)
reader := bufio.NewReader(os.Stdin)
value, _ := reader.ReadString(&#39;\n&#39;)
fmt.Println(value)

If you were to run that with $ ./goexecutable &gt; result.txt

The content of result.txt will look like Please enter a value: value\n

Is there an equivalent in go to the bash &lt;PROMPT&gt; string from read -p which prints to the command line, but not to stdout?

答案1

得分: 6

Bash的read -p只是将提示打印到stderr。你可以通过将脚本的stderr重定向到/dev/null,然后注意到没有提示打印出来来进行判断。

./bashfile > result.txt 2> /dev/null

在Go语言中,你可以使用fmt.Fprintf来实现相同的效果。

fmt.Fprintf(os.Stderr, "请输入一个值:")
英文:

Bash's read -p just prints the prompt to stderr. You can tell by redirecting the stderr of your script to /dev/null and noticing that no prompt prints.

 ./bashfile &gt; result.txt 2&gt; /dev/null

You can do the same in Go using fmt.Fprintf.

fmt.Fprintf(os.Stderr, &quot;Please enter a value: &quot;)

huangapple
  • 本文由 发表于 2016年3月16日 12:50:10
  • 转载请务必保留本文链接:https://go.coder-hub.com/36027021.html
匿名

发表评论

匿名网友

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

确定