英文:
python subprocess stdin truncated at first space
问题
我对pOpen.communicate()
有一个问题,就是我发送给子进程的字符串在第一个空格字符处截断(请记住,我使用utf-8
编码为字节)。
输入文件text.txt
:
this is an input string
我的代码:
from subprocess import Popen, PIPE
# 打开文件并将其编码为utf-8字节
fp = open('test.txt')
inputs = fp.read()
inputBytes = bytes(inputs, 'utf-8')
# 打开子程序并将字节发送到STDIN
p = Popen(['./program'], stdout=PIPE, stdin=PIPE, stderr=PIPE)
stdout_data = p.communicate(input=inputBytes)
# 打印子进程的STDOUT,将打印给定的内容
out = str(stdout_data).split('\n')
for frame in out:
print(frame)
我的预期输出:
(b'this is an input string', b'')
我得到的输出:
(b'this', b'')
我是否使用了错误的编码格式?子程序是一个使用scanf
监听pOpen.communicate()
数据的Go应用程序。
package main
import "fmt"
func main() {
var inputs string
fmt.Print("")
fmt.Scanf("%s", &inputs)
fmt.Println(inputs)
}
英文:
I have an issue with pOpen.communicate()
where the string I send to the subprocess truncates at the first occurrence of a space character I am sending to STDIN
(keep in mind I am encoding to bytes using encoding utf-8
)
Input file text.txt
this is an input string
My code
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)
my expected output:
(b'this is an input string', b'')
what I got:
(b'this', b'')
am I using the wrong encoding format? The subprogram is a go application that uses scanf to listen to pOpen.communicate() data
package main
import "fmt"
func main() {
var inputs string
fmt.Print("")
fmt.Scanf("%s", &inputs)
fmt.Println(inputs)
}
答案1
得分: 1
Go的fmt.Scanf
基于C的scanf
;%s
会跳过前导空格,然后读取下一个单词直到第一个空格。这可能不是你想要的。
根据文档,更加精确的解释是:
由动词处理的输入隐式以空格分隔:除了
%c
之外的每个动词的实现都会从剩余输入中丢弃前导空格,而%s
动词(以及读入字符串的%v
)会在第一个空格或换行符处停止消耗输入。(https://pkg.go.dev/fmt)
英文:
Go's fmt.Scanf
is based on C's scanf
; %s
skips leading spaces and then reads the next word up to the first space. That's probably not what you wanted.
From the docs, a bit more precise:
> Input processed by verbs is implicitly space-delimited: the implementation of every verb except %c
starts by discarding leading spaces from the remaining input, and the %s
verb (and %v
reading into a string) stops consuming input at the first space or newline character. (https://pkg.go.dev/fmt)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论