英文:
Golang: Command Prompt
问题
我正在编写一个个人工具,它给我提供一个提示,并允许我执行有用的命令。就像Bash一样,但它不是一个shell程序。
我想要一个像Bash一样的输入提示。
如果你什么都不输入,只需打印一个新行并再次扫描输入。
如果你输入热键<kbd>Ctrl + D</kbd>,终止程序。
应该是这样的:
[user@computer ~]$ go build
[user@computer ~]$ ./myapp
$
$ command
.. 执行命令
$ (Ctrl + D 热键)
[user@computer ~]$
我尝试使用Scanln,但它不接受空格,这是一个很大的问题。
编辑:这是我实现的代码
func main() {
var input string
fmt.Println(banners.Gecko1)
fmt.Print("$ ")
fmt.Scanln(&input)
}
这是控制台输出:
[user@pc MyTool]$ go build
[user@pc MyTool]$ ./MyTool
-----输入命令
$ term1 term2 term3 term4 term5
[user@pc MyTool]$ erm2 term3 term4 term5
bash: erm2: command not found
[user@pc MyTool]$
如你所见,term1之后的所有内容都被忽略,并且以某种方式传递给了bash...
英文:
I am writing a personal tool which gives me a prompt and lets me execute useful commands. Like bash but its not a shell program
I want an input prompt like Bash
If you enter nothing, just print a new line and scan for input again
If you enter the hotkey <kbd>Ctrl + D</kbd>, terminate the program
It should be like this
[user@computer ~]$ go build
[user@computer ~]$ ./myapp
$
$ command
.. do command
$ (Ctrl + D hotkey)
[user@computer ~]$
I tried using Scanln but it didn't accept spaces which was a huge problem
EDIT: here is what I implemented
func main() {
var input string
fmt.Println(banners.Gecko1)
fmt.Print("$ ")
fmt.Scanln(&input)
}
Here is the console:
[user@pc MyTool]$ go build
[user@pc MyTool]$ ./MyTool
-----ENTER COMMANDS
$ term1 term2 term3 term4 term5
[user@pc MyTool]$ erm2 term3 term4 term5
bash: erm2: command not found
[user@pc MyTool]$
as you can see, everything after term1 is ignored and somehow passed to bash...
答案1
得分: 2
我认为这就是scanln
应该工作的方式。文档中指出,它“从标准输入中扫描文本,将连续的以空格分隔的值存储到连续的参数中。”如果你想一次读取一行,可以使用bufio
包。你可以参考下面的示例代码:
package main
import (
"bufio"
"fmt"
"os"
"strings"
)
func main() {
input_reader := bufio.NewReader(os.Stdin)
for {
fmt.Print("$ ")
line, _ := input_reader.ReadString('\n')
line = strings.Replace(line, "\n", "", -1)
fmt.Println(line)
}
}
英文:
I think that's how scanln is supposed to work. The docs state that it "scans text from standard input, storing successive space-separated values into successive arguments." Alternatively, use the bufio package if you want to read one line at a time. You can refer to the sample code below:
package main
import (
"bufio"
"fmt"
"os"
"strings"
)
func main() {
input_reader := bufio.NewReader(os.Stdin)
for {
fmt.Print("$ ")
line, _ := input_reader.ReadString('\n')
line = strings.Replace(line, "\n", "", -1)
fmt.Println(line)
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论