从 golang 应用程序发送字符串时出现意外的 StrComp 结果

Unexpected StrComp result when string is sent from golang app

在我下面的代码中,我设置了一个 ReadString,它读取用户输入并在 exec.Command 中传递它。

这很好用,但是当我尝试将字符串与 vbscript 中的硬编码字符串进行比较时(在本例中,我将其与 "hello" 进行比较),即使用户输入 "hello" 还有。

如果我像这样通过命令行 运行 vbscript 但是...

 cscript.exe script.vbs hello

...然后 StrComp 按预期工作,所以我怀疑这是数据类型问题,或者在 golang 应用程序中传递了一些额外的字符。

这是main.go:

package main

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

func main() {

    buf := bufio.NewReader(os.Stdin)

    fmt.Print("Type something: ")
    text, err := buf.ReadString('\n')
    if err != nil {
        fmt.Println(err)
    } else {
        args := []string{"./script.vbs", string(text)}
        exec.Command("cscript.exe", args...).Run()
    }
}

这里是 script.vbs

MsgBox(WScript.Arguments(0))

If StrComp(WScript.Arguments(0), "hello") = 0 Then
    MsgBox("it's the same")
Else
    MsgBox("It's not the same...")
End If

使用 windows 时,行尾为“\r\n”。我不知道 ReadString() 是否应该删除定界符,但即便如此,文本仍将包含一个不可见的 \r。使用strings.TrimSpace在保存端:

package main

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

func main() {

    buf := bufio.NewReader(os.Stdin)

    fmt.Print("Type something: ")
    text, err := buf.ReadString('\n')
    fmt.Printf("0 got: %T %v %q\r\n", text, text, text)
    text = strings.TrimSpace(text)
    fmt.Printf("1 got: %T %v %q", text, text, text)
    if err != nil {
        fmt.Println(err)
    } else {
        args := []string{"./script.vbs", string(text)}
        exec.Command("cscript.exe", args...).Run()
    }
}

输出(主要;发挥您对 VBScript MsgBox 的想象力):

main
Type something: hello
0 got: string hello
 "hello\r\n"
1 got: string hello "hello"