Golang中如何运行 " > 命令
Golang中如何运行 " > 命令 如何运行“先生,我的引号“quotequotequotequotequotequotequotequotequote””
package main
import "fmt"
func main() {
fmt.Println(" HE >_< = “< llo, 世界”)
}
5 回复
抱歉,但具体的问题是什么?
起初我以为你想要的是shell重定向,但你的示例代码只是一些奇怪的、半成品的println。
另外,请使用三个反引号来包裹代码,或者额外缩进四个空格,以便论坛软件及其渲染引擎能够识别你的代码片段:
就像这样
使用原始字符串字面量。
package main
import "fmt"
func main() {
fmt.Println(` HE >_< = “< llo, 世界`)
}

Go Playground - The Go Programming Language
HE >_< = “< llo, 世界
字符串字面量
字符串字面量表示通过连接一系列字符获得的字符串常量。有两种形式:原始字符串字面量和解释型字符串字面量。
原始字符串字面量是反引号之间的字符序列,例如
foo。在引号内,除了反引号外,任何字符都可以出现。原始字符串字面量的值是由引号之间未解释的(隐式 UTF-8 编码的)字符组成的字符串;特别是,反斜杠没有特殊含义,并且字符串可以包含换行符。原始字符串字面量中的回车符(’\r’)会从原始字符串值中丢弃。
在Golang中运行包含特殊引号的命令,可以使用exec.Command配合适当的引号处理。对于你提供的代码,主要问题是字符串中的引号格式不正确。
package main
import (
"fmt"
"os/exec"
)
func main() {
// 方法1: 直接使用反引号处理包含特殊引号的字符串
cmd := exec.Command("echo", `先生,我的引号“quotequotequotequotequotequotequotequotequote”`)
output, err := cmd.Output()
if err != nil {
fmt.Println("命令执行错误:", err)
return
}
fmt.Printf("输出: %s", output)
// 方法2: 修复你的原始代码中的字符串问题
fmt.Println(" HE >_< = \"< llo, 世界\"")
// 方法3: 执行包含特殊字符的shell命令
cmd2 := exec.Command("sh", "-c", `echo "先生,我的引号“quotequotequotequotequotequotequotequotequote”"`)
output2, err := cmd2.Output()
if err != nil {
fmt.Println("命令执行错误:", err)
return
}
fmt.Printf("Shell输出: %s", output2)
}
对于包含特殊引号的字符串,建议使用反引号()来定义原始字符串,这样可以避免转义问题。如果要执行外部命令,使用exec.Command`并确保参数正确传递。


