python子进程stdin在第一个空格处截断



我有一个pOpen.communicate()的问题,其中我发送到子进程的字符串在我发送到STDIN的空格字符的第一次出现时截断(请记住,我使用编码utf-8编码到字节)

输入文件text.txt

this is an input string

我的代码
from subprocess import Popen, PIPE
# open file and encode to utf-8 bytes
fp = open('test.txt')
inputs = fp.read()
inputBytes = bytes(inputs, 'utf-8')
# open subprogram and send the bytes to STDIN
p = Popen(['./program'], stdout=PIPE, stdin=PIPE, stderr=PIPE)
stdout_data = p.communicate(input=inputBytes)
# print STDOUT of subprocess, will print what was given
out = str(stdout_data).split('\n')
for frame in out:
print(frame)

我的期望输出:

(b'this is an input string', b'')

我得到了什么:

(b'this', b'')

我是否使用了错误的编码格式?子程序是一个go应用程序,它使用scanf来监听popen . communication()数据

package main
import "fmt"

func main() {
var inputs string
fmt.Print("")
fmt.Scanf("%s", &inputs)
fmt.Println(inputs)
}

Go的fmt.Scanf是基于C的scanf;%s跳过前导空格,然后读取下一个单词直到第一个空格。这可能不是你想要的。

从文档中,更精确一点:

由动词处理的输入隐式地以空格分隔:除了%c之外,每个动词的实现都从丢弃剩余输入中的前导空格开始,%s动词(和%v读入字符串)在第一个空格或换行符处停止使用输入。(https://pkg.go.dev/fmt)

最新更新