英文:
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 "Please enter a value: " value
echo "${value}"
If this file is then executed like $ ./bashfile > 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("Please enter a value: ")
reader := bufio.NewReader(os.Stdin)
value, _ := reader.ReadString('\n')
fmt.Println(value)
If you were to run that with $ ./goexecutable > 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 <PROMPT>
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 > result.txt 2> /dev/null
You can do the same in Go using fmt.Fprintf
.
fmt.Fprintf(os.Stderr, "Please enter a value: ")
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论