登录
首页 >  Golang >  Go问答

为什么在 Go 中 exec.Command() 失败,而 os.StartProcess() 成功启动“winget.exe”?

来源:stackoverflow

时间:2024-02-20 16:00:29 310浏览 收藏

本篇文章给大家分享《为什么在 Go 中 exec.Command() 失败,而 os.StartProcess() 成功启动“winget.exe”?》,覆盖了Golang的常见基础知识,其实一个语言的全部知识点一篇文章是不可能说完的,但希望通过这些问题,让读者对自己的掌握程度有一定的认识(B 数),从而弥补自己的不足,更好的掌握它。

问题内容

  • exec.command() 用于执行 c:\windows\system32\notepad.exe
  • 但是 exec.command() 不适用于执行 c:\users\\appdata\local\microsoft\windowsapps\winget.exe。失败并显示错误消息:
    • exec:“c:\\users\\\\appdata\\local\\microsoft\\windowsapps\\winget.exe”:文件不存在
  • 但是,os.startprocess() 适用于执行 c:\users\\appdata\local\microsoft\windowsapps\winget.exe

谁能告诉我为什么?

该代码片段不起作用。 winget.exe 未启动。

wingetpath := filepath.join(os.getenv("localappdata"),
    "microsoft\\windowsapps\\winget.exe")
cmd := exec.command(wingetpath, "--version")
err := cmd.start()
fmt.println(err)
// exec: "c:\\users\\\\appdata\\local\\microsoft\\windowsapps\\winget.exe": file does not exist

但这有效:

wingetpath := filepath.join(os.getenv("localappdata"),
    "microsoft\\windowsapps\\winget.exe")
procattr := new(os.procattr)
procattr.files = []*os.file{nil, nil, nil}

// the argv slice will become os.args in the new process,
// so it normally starts with the program name
_, err := os.startprocess(wingetpath, []string{wingetpath, "--version"}, procattr)
fmt.println(err)
// 

go 版本:

> go version
go version go1.18 windows/amd64

正确答案


golang 中的错误

很明显,这是 go 的 windows 实现中的一个错误,并且已在 github 上多次提交 - 我能找到的最早的是几年前提交的 issue

该错误是由 exec.command() 内部 uses os.stat() 无法正确读取 reparse points 的文件引起的。 os.lstat() 可以。

windows 应用商店应用程序使用 App Execution Aliases,它们本质上是带有重分析点的零字节文件。此 post 有一些额外的详细信息。

解决方法

  • 解决方法是使用 os.startproces() - 一个较低级别的 api,使用起来可能有点痛苦,尤其是与 os.exec() 相比。
    重要:在os.startprocess()中,argv切片将在新进程中变为os.args,因此您通常应该将程序名称作为第一个参数传递:
wingetPath := filepath.Join(os.Getenv("LOCALAPPDATA"),
    "Microsoft\\WindowsApps\\winget.exe")
procAttr := new(os.ProcAttr)
procAttr.Files = []*os.File{nil, nil, nil}
/*
To redirect IO, pass in stdin, stdout, stderr as required
procAttr.Files = []*os.File{os.Stdin, os.Stdout, os.Stderr}
*/

args = []string { "install", "git.git" }

// The argv slice will become os.Args in the new process,
// so it normally starts with the program name
proc, err := os.StartProcess(wingetPath,
   append([]string{wingetPath}, arg...), procAttr)
fmt.Println(err) // nil
  • 解决此错误的另一种方法是(创建并)执行 .cmd 文件(例如),该文件将(正确解析并)执行带有重新分析点的文件。有关示例,请参阅 this(以及此 directory)。

到这里,我们也就讲完了《为什么在 Go 中 exec.Command() 失败,而 os.StartProcess() 成功启动“winget.exe”?》的内容了。个人认为,基础知识的学习和巩固,是为了更好的将其运用到项目中,欢迎关注golang学习网公众号,带你了解更多关于的知识点!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>