【问题标题】:Capturing the output of exec.Command("find", "./helloworld/workspace", "-name", "*.java").Output()捕获 exec.Command("find", "./helloworld/workspace", "-name", "*.java").Output() 的输出
【发布时间】:2021-03-11 16:29:41
【问题描述】:

我正在尝试查找 helloworld.java 文件的路径,以便将其传递给编译器函数。

我有什么:

我希望这会返回此目录中唯一 helloworld.java 文件的 []byte 类型的路径,然后将其字符串化,然后将其传递给 Java() 函数。

filePath, _ := exec.Command("find", "./helloworld/workspace", "-name", "*.java").Output()
                    
Java(string(filePath))

问题是我的 java() 函数中的 cmd := exec.Command("javac", filePath) 无法识别文件路径,因此无法编译它。 但是,如果我像这样对从 exec.Command("find) 获得的路径进行硬编码: 这很好用

cmd := exec.Command("javac", "./helloworld/workspace/src/main/java/com/coveros/demo/helloworld/HelloWorld.java")
err := cmd.Run()

但这不起作用:

我错过了什么,我该如何解决这个问题?

func Java(filePath string) {
    fmt.Println("compiler start")
    cmd := exec.Command("javac", filePath)
    err := cmd.Run()

    if err != nil {
        log.Fatal(err)
    }
        fmt.Println("compiler End")
}

【问题讨论】:

  • string(filePath) 的输出是什么?
  • @Christian 输出是java文件的路径:./helloworld/workspace/src/main/java/com/coveros/demo/helloworld/HelloWorld.java
  • 但是这个的实际输出是什么:fmt.Println(string(filePath)) 这是否显示了文件的正确路径?
  • 是的,如果我运行 fmt.Println(string(filePath)) 它会显示我上面提到的路径。这就是为什么如果它清楚地返回我需要的东西对我来说不起作用。不确定我是否遗漏了什么
  • 你确定当前工作目录在这两种情况下都是一样的吗? (即您的程序在此期间没有更改目录?)

标签: go


【解决方案1】:

我认为find 的结果是返回多个可能的路径,这些路径由换行符"\n" 分隔。如果将换行符打印到命令行,它将被“隐藏”。你可以试试这个fmt.Println(stringPath + "hello, am I on a new line?") 来显示stringPath 里面有一个新行。

见下文,它使用类似版本的 find 查找 json 文件,然后用换行符分割字符串,然后循环遍历这些路径。如果路径是空白的(可以是),它会跳过它。

package main

import (
    "fmt"
    "os/exec"
    "strings"
)

func main() {
    filePath, err := exec.Command("find", ".", "-name", "*.json").Output()
    if err != nil {
        panic(err)
    }

    stringPath := string(filePath)
    paths := strings.Split(stringPath, "\n")

    CatFile(paths)
}

func CatFile(filePaths []string) {
    for _, path := range filePaths {
        if len(path) == 0 {
            continue
        }
            output, err := exec.Command("cat", path).Output()
        if err != nil {
            fmt.Println("Error!")
            fmt.Println(err)
        }
        fmt.Println(string(output))
    }
}

查看这个相关问题,其中讨论了这个问题:Go lang differentiate "\n" and line break

【讨论】:

  • 是的,就是这样。谢谢!
猜你喜欢
  • 1970-01-01
  • 2010-11-10
  • 2021-12-25
  • 1970-01-01
  • 2023-03-31
  • 2014-07-08
  • 2011-06-09
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多