Golang:命令提示符

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

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(&quot;$ &quot;)
	fmt.Scanln(&amp;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 (
	&quot;bufio&quot;
	&quot;fmt&quot;
	&quot;os&quot;
	&quot;strings&quot;
)

func main() {
	input_reader := bufio.NewReader(os.Stdin)
	for {
		fmt.Print(&quot;$ &quot;)
		line, _ := input_reader.ReadString(&#39;\n&#39;)
		line = strings.Replace(line, &quot;\n&quot;, &quot;&quot;, -1)
		fmt.Println(line)
	}
}

huangapple
  • 本文由 发表于 2022年11月23日 02:12:01
  • 转载请务必保留本文链接:https://go.coder-hub.com/74537297.html
匿名

发表评论

匿名网友

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

确定