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")
以上就是尝试使用 exec.Command 运行 gofmt -r 时出现“符文文字未终止”错误的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号