你如何在Golang中执行终端命令?

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

How do you execute terminal commands from Golang?

问题

我正在使用Golang创建一个CLI工具,对于Golang和制作终端工具我都是新手。我需要从我的程序中执行终端命令(特别是cd命令)。我按照这个帖子的步骤进行操作,但是它报错说在%path%中找不到echo命令。

非常感谢您提前的帮助!

英文:

I'm creating a CLI tool in Golang, and I'm new to both Golang and making tools for the terminal. I need to execute terminal commands right from my program (specifically cd). How do I do this? I followed along with this post, but it threw an error saying that echo wasn't found in %path%

Thanks in advance for any help!

答案1

得分: 4

os/exec 包可以帮助你在 Go 中执行终端命令。

执行系统命令非常简单。Cmd 结构体保存了你的外部命令。

所以在 Linux 中,假设你想要运行 "echo hello" 命令,你可以编写以下代码。

cmdStruct := exec.Command("echo", "hello")
out, err := cmdStruct.Output()
if err != nil {
    fmt.Println(err)
}
fmt.Println(string(out))

这是最基本的方法之一。然而,在 Windows 中,你需要将 "echo hello" 作为参数传递给命令提示符或 PowerShell。

cmdStruct := exec.Command("cmd.exe", "/c", "echo", "hello")

为了简化这个过程,你可以将参数放在一个切片中:

args := strings.Split("/c echo hello there how are you", " ")
cmdStruct := exec.Command("cmd.exe", args...)

查看这个答案可以更好地理解和改进这段代码。

对于 cd 命令,你可以使用 os.Chdir()os.Getwd() 分别来更改和查看你的工作目录。但是,如果你需要在特定目录中执行命令,你可以设置命令的 Dir 属性,例如:

cmdStruct.Dir = "path/to/directory"

或者

cmdStruct.Dir = filepath.Join("path", "to", "directory")
英文:

os/exec package helps you execute terminal commands in Go.

Executing system commands is quite simple. Cmd holds your external command.

So in linux suppose you want to run "echo hello" command, you'd write the following code.

cmdStruct := exec.Command("echo","hello")    
out,err := cmdStruct.Output()
if err != nil {
    fmt.Println(err)
}
fmt.Println(string(out))

This is one of the most basic way. However, in Windows, you need to pass "echo hello" as an argument to Command prompt or Powershell.

    cmdStruct:= exec.Command("cmd.exe","/c","echo","hello")

To simplify this pass arguments in a single slice,

args:= strings.Split("/c echo hello there how are you"," ")
cmdStruct:= exec.Command("cmd.exe",args...)

Check out this answer for a better understanding and an enhanced version of this code.

For cd you can use os.Chdir() and os.Getwd() to change and view your working directory respectively. But if you require your command to execute in a specific directory tou can set Dir of your command i.e.

cmdStruct.Dir = "path/to/directory"

or

cmdStruct.Dir = filepath.Join("path","to","directory")

答案2

得分: 2

通过调用os.Chdir来实现cd命令。

由于子进程无法更改父进程的工作目录,因此cd命令没有单独的可执行文件。cd命令是内置于命令行解释器中的。

英文:

Implement the cd command by calling os.Chdir.

Because a subprocess cannot change the working directory of a parent process, there is not a separate executable for the cd command. The cd command is builtin to command line interpreters.

答案3

得分: 1

cd不是一个外部程序。

命令行解释器有一个抽象的“当前目录”,它会影响所有其他命令。这是一个状态

它用于处理相对路径,例如。

如果你想从头开始创建自己的命令行界面,你必须定义这个状态如何影响一切。

如果你需要与现有的命令行界面进行交互,你需要在一个操作系统进程中启动它,并通过流进行交互。

有三个流:

STDIN - 输入
STDOUT - 输出
STDERR - 错误

你需要捕获用户的命令并发送到命令行界面的STDIN。并读取STDIN / STDOUT来编写响应。

这涉及到使用goroutines,例如

英文:

cd is not a external program.

The command line interpreter has an abstraction “current dir”, that affects all other commands. It is a state

It is used to handle relative paths, for instance.

If you want to create your CLI from scratch you must define how this stage affects everything.

If you need to interact to an existing CLI, you need to start it in a OS process and interact via streams.

There are 3 streams:

STDIN - input
STDOUT - output
STDERR - for error

You need to capture the user commands and send to the STDIN of the CLI. And read both STDIN / STDOUT to write a response.

This is something to do with goroutines, for instance

答案4

得分: 1

尽管我问了很久,但我觉得回答这个问题还是好的。简单来说,没有办法。程序基本上在它们自己的小容器中运行,这意味着虽然os.Chdir()在技术上可以改变工作目录,但它在之后会“恢复回来”。

英文:

Even though it's been quite a while since I asked this, I figured it would be good to answer this. To put it simply, there's no way. Programs essentially run on their own little contained box, which means while os.Chdir() does technically change the working directory, it "reverts back" afterwards.

huangapple
  • 本文由 发表于 2022年4月3日 10:27:08
  • 转载请务必保留本文链接:https://go.coder-hub.com/71722546.html
匿名

发表评论

匿名网友

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

确定