英文:
Go syscall.Exec running psql - no such file or directory
问题
我正在使用Go调用psql
命令。运行时出现以下错误:
没有这个文件或目录
在终端中,该命令可以正常运行,只有在从Go中运行时才会出现此错误。
这是我的代码:
package main
import (
"fmt"
"os"
"syscall"
)
func main() {
args := []string{"psql", "--version"}
fmt.Println(args)
error := syscall.Exec("psql", args, os.Environ())
// 我们不希望它返回;如果它返回了,说明出现了严重错误
panic(error)
}
以及输出:
❯ go run main.go
[psql --version]
panic: no such file or directory
goroutine 1 [running]:
main.main()
/Users/myuser/development/golang/go_rds/main.go:16 +0xc8
exit status 2
我感觉我没有理解Go调用psql的方式。
英文:
I am using Go to invoke the psql
command. When running it I get the error:
no such file or directory
The command works fine in the terminal, it's only when running from Go do I see this error.
This is my code:
package main
import (
"fmt"
"os"
"syscall"
)
func main() {
args := []string{"psql", "--version"}
fmt.Println(args)
error := syscall.Exec("psql", args, os.Environ())
// We don't expect this to ever return; if it does something is really wrong
panic(error)
}
and the output:
❯ go run main.go
[psql --version]
panic: no such file or directory
goroutine 1 [running]:
main.main()
/Users/myuser/development/golang/go_rds/main.go:16 +0xc8
exit status 2
I feel I am not understanding the way Go is calling psql.
答案1
得分: 1
问题是“Go需要一个绝对路径来执行我们想要执行的二进制文件”。
为了修复它,我只是添加了以下代码:
binary, lookErr := exec.LookPath("psql")
if lookErr != nil {
panic(lookErr)
}
现在它按预期执行了。
英文:
Issue was Go requires an absolute path to the binary we want to execute
To fix it I have just added:
binary, lookErr := exec.LookPath("psql")
if lookErr != nil {
panic(lookErr)
}
And now this executes as expected.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论