登录
首页 >  Golang >  Go问答

使用正确的参数在Go中运行外部程序

来源:stackoverflow

时间:2024-02-14 09:09:23 113浏览 收藏

积累知识,胜过积蓄金银!毕竟在Golang开发的过程中,会遇到各种各样的问题,往往都是一些细节知识点还没有掌握好而导致的,因此基础知识点的积累是很重要的。下面本文《使用正确的参数在Go中运行外部程序》,就带大家讲解一下知识点,若是你对本文感兴趣,或者是想搞懂其中某个知识点,就请你继续往下看吧~

问题内容

晚上好, 我正在努力将一些用 python 编写的工具转换为 go,以便更好地理解它。

我需要程序使用一些参数调用外部 .exe,以便它正确格式化一些数据。在 windows shell 中我可以执行 c:\path_to_exe\file.exe arg1 arg2 "c:\path_to_output\output.txt"

我相信在 go 中执行此操作的正确方法是使用 exec.command,但我没有得到任何...有意义的结果。

out, err := exec.command("cmd", "c:\\path\\tools\\util\\utility.exe c:\\file_location \"select * from table\" c:\\output_path\\output.txt").output()

            fmt.printf("\n", string(out))

            if err != nil {
                println(" error running decomp ", err)
            }

这似乎正在运行命令,因为我收到的输出是:

%!(extra string=microsoft windows [version 10.0.22000.739]
(c) microsoft corporation. all rights reserved.
process finished with the exit code 0

只是为了咯咯笑,我尝试打破争论,但得到了相同的结果

out, err := exec.Command("cmd", exPath, utilPath, statement, textOutputPath+"test.txt").Output()

我期望执行的程序运行,根据输入解析正确的文件,并输出指定的txt文件。我没有留下 .txt 文件,并且 go 程序的运行速度比解析要快得多。

一定是我遗漏了一些东西,有人可以提供一些有关 exec.command 的正确用法的见解吗?因为我能找到的每个示例似乎都表明这应该有效。


正确答案


为什么要生成 cmd.exe 并让它运行 utility.exe

您可以单独生成 utility

例如,假设您有两个二进制文件 hellosay-hello 位于同一目录中,编译自

  • hello.gohello

    package main
    
    import (
      "fmt"
      "os"
    )
    
    func main() {
    
      argv := os.args[1:]
      if len(argv) == 0 {
        argv = []string{"world"}
      }
    
      for _, arg := range argv {
        fmt.printf("hello, %s!\n", arg)
      }
    
    }
  • say-hello.gosay-hello

    package main
    
    import (
      "fmt"
      "os"
      "os/exec"
    )
    
    func main() {
      process := exec.command("./hello", os.args[1:]...)
      process.stdin = os.stdin
      process.stdout = os.stdout
      process.stderr = os.stderr
    
      if err := process.run(); err != nil {
        fmt.printf("command failed with exit code %d\n", process.processstate.exitcode())
        fmt.println(err)
      }
    }

然后您可以运行命令:

$ ./say-hello arawn gywdion sarah hannah

并得到预期的结果

hello, arawn!
hello, gwydion!
hello, sarah!
hello, hannah!

根据您问题中的输出,它似乎工作正常。

一些建议:

  • 在运行之前将命令以字符串形式打印出来可能会很有用,以检查它是否是您想要的。
  • 当您的字符串包含反斜杠和引号时,您可能会发现反引号很有用。
  • 您尚未向 fmt.printf 提供任何格式,因此该输出中为 extra
  • 使用 println 打印错误不会将其字符串化,因此也可以使用 fmt.printf 来打印错误。
package main

import (
    "fmt"
    "os/exec"
)

func main() {
    cmd := exec.Command("cmd", `C:\path\tools\util\Utility.exe C:\file_Location "select * from TABLE" C:\output_path\output.txt`)
    fmt.Printf("%s\n", cmd.String())
    out, err := cmd.Output()
    fmt.Printf("%s\n", string(out))
    if err != nil {
        fmt.Printf(" Error running decomp %s\n", err)
    }
}

演示:https://go.dev/play/p/3t0aOxAZRtU

以上就是本文的全部内容了,是否有顺利帮助你解决问题?若是能给你带来学习上的帮助,请大家多多支持golang学习网!更多关于Golang的相关知识,也可关注golang学习网公众号。

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