英文:
Cannot run "git" with exec.Command()
问题
我想运行 exec.Command("git", "config", "--global", "user.name")
并读取输出。
在Windows上,单词 git
被翻译为 git 路径 (C:\Program Files\...\git.exe
)。然后它尝试运行 C:\Program
(这不是可执行文件的路径)。
我尝试过对空格进行转义,尝试在路径周围添加括号,或者只在空格周围添加括号并对它们进行转义。但都没有成功。
arg0 := "config"
arg1 := "--global"
arg2 := "\"user.name\""
bcmd := exec.Command("git", arg0, arg1, arg2)
var stdout bytes.Buffer
bcmd.Stdout = &stdout
err := bcmd.Run()
我尝试添加括号,但没有帮助。
英文:
I want to run exec.Command("git", "config", "--global", "user.name")
and read the output.
On windows the word "git"
translates to the git path (C:\Program Files\...\git.exe
). Then it tries to run C:\Program
(which is not a path to an executable).
I have tried escaping the space, I have tried to add parentheses around the path, or only around the space and escape them. Nothing worked.
arg0 := "config"
arg1 := "--global"
arg2 := "\"user.name\""
bcmd := exec.Command("git", arg0, arg1, arg2)
var stdout bytes.Buffer
bcmd.Stdout = &stdout
err := bcmd.Run()
I have tried adding parentheses and it did not help.
答案1
得分: 1
你不应该对arg2
使用引号。至于读取输出,这取决于你对读取的理解。输出将被写入缓冲区,即在你的情况下是stdout
。你可以使用stdout.Bytes()
获取输出的字节,如果你想要实际的string
(我假设你实际上想要的是这个),你可以使用string(stdout.Bytes())
进行类型转换。
package main
import (
"bytes"
"fmt"
"log"
"os/exec"
)
func main() {
bcmd := exec.Command("git", "config", "--global", "user.name")
var stdout bytes.Buffer
bcmd.Stdout = &stdout
err := bcmd.Run()
if err != nil {
log.Fatal(err)
}
fmt.Printf(string(stdout.Bytes()))
}
还有另一种更简单的方法可以实现相同的功能,使用Output()
。
package main
import (
"fmt"
"log"
"os/exec"
)
func main() {
outputBytes, err := exec.Command("git", "config", "--global", "user.name").Output()
if err != nil {
log.Fatal(err)
}
fmt.Printf(string(outputBytes))
}
这两种方法都会打印出你的git用户名。
英文:
You should not use quotes for arg2
. As for reading the output it depends what you understand by reading. The output will be written to the buffer which is stdout
in your case. You can obtain the bytes of the output using stdout.Bytes()
and if you want the actual string
(which I assume you actually want) you can just cast to string
using string(stdout.Bytes())
.
package main
import (
"bytes"
"fmt"
"log"
"os/exec"
)
func main() {
bcmd := exec.Command("git", "config", "--global", "user.name")
var stdout bytes.Buffer
bcmd.Stdout = &stdout
err := bcmd.Run()
if err != nil {
log.Fatal(err)
}
fmt.Printf(string(stdout.Bytes()))
}
There also is another simpler way to do the same thing using Output()
.
package main
import (
"fmt"
"log"
"os/exec"
)
func main() {
outputBytes, err := exec.Command("git", "config", "--global", "user.name").Output()
if err != nil {
log.Fatal(err)
}
fmt.Printf(string(outputBytes))
}
Both will print your git username.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论