pythongo

Can't print Chinese if using Go to exec python scripts


I use below command to run python 3.7.4 file via Go.

Go exec.Command("cmd", "/C", "path_to_python_exe", "python_script_file")

Below script will print "abc" without the Chinese:

print ("abc")
print ("系统")

and it print nothing and return no error:

print ("系统")
print ("abc")

When I run "python test.py" in windows/linux terminal, it works well.

I get the output with go as below:

stdout, err := cmd.StdoutPipe()
cmd.Start()

reader := bufio.NewReader(stdout)
output := make([]string, 0)
for {
    line, err2 := reader.ReadString('\n')
    if err2 != nil || io.EOF == err2 {
        break
    }
    output = append(output, line)
}

cmd.Wait()

return strings.Join(output, "")

Solution

  • Add below codes, it works well:

    import sys,io,platform
    if(platform.system()=='Windows'):
        sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8')
        sys.stderr = io.TextIOWrapper(sys.stderr.buffer, encoding='utf-8')