运行 psql 时出现错误:没有这个文件或目录。

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

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.

huangapple
  • 本文由 发表于 2023年3月15日 21:01:24
  • 转载请务必保留本文链接:https://go.coder-hub.com/75745089.html
匿名

发表评论

匿名网友

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

确定