卓越飞翔博客卓越飞翔博客

卓越飞翔 - 您值得收藏的技术分享站
技术文章35387本站已运行395

尝试使用 exec.Command 运行 gofmt -r 时出现“符文文字未终止”错误

尝试使用 exec.command 运行 gofmt -r 时出现“符文文字未终止”错误

php小编柚子在使用exec.Command运行gofmt -r时,遇到了"符文文字未终止"错误。该错误可能是由于命令中的某个符号未正确终止导致的。为了解决这个问题,我们可以检查命令中的符号是否正确配对,并确保每个符号都有正确的终止符。另外,还可以尝试使用转义字符来处理包含特殊符号的命令。希望这些方法能帮到遇到同样问题的开发者们!

问题内容

在以下目录结构中,

.
├── foo.go
├── go.mod
└── main.go

我有一个 foo.go ,它具有简单的类型定义:

package main

type foo struct {
    baz string
}

如果我从命令行运行 ngofmt -r 来替换变量名称,它会起作用:

> gofmt -r 'foo -> bar' foo.go
package main

type bar struct {
    baz string
}

但是,如果我尝试使用该程序从 main.go 执行此操作

package main

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

func main() {
    combinedoutput, err := exec.command("gofmt", "-r", "'foo -> bar'", "foo.go").combinedoutput()
    if err != nil {
        log.fatalf("gofmt foo.go: %v. combined output: %s", err, combinedoutput)
    }
    fmt.println(string(combinedoutput))
}

我收到错误:

> go run main.go
2023/01/14 23:42:07 gofmt foo.go: exit status 2. Combined output: parsing pattern 'Foo  at 1:1: rune literal not terminated
exit status 1

知道是什么原因造成的吗?

解决方法

您不需要引用 exec.command 的参数;引用是 shell 的一项功能,在进行系统调用时不适用。也没有必要,因为在 shell 中引用是为了描述参数,但在 exec.command 中,参数被分隔为函数调用的参数。

具体:

exec.command("gofmt", "-r", "'foo -> bar'", "foo.go")

应该是

exec.Command("gofmt", "-r", "Foo -> Bar", "foo.go")
卓越飞翔博客
上一篇: Go 中的 Pact 消费者测试。 dsl.Match 函数的问题
下一篇: 返回列表
留言与评论(共有 0 条评论)
   
验证码:
隐藏边栏