You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用subprocess.Popen.communicate()时STDIN内容遇空格截断问题

问题:使用Popen.communicate()向子进程发送字符串时被空格截断

我在使用Popen.communicate()向子进程的STDIN发送字符串时遇到问题:发送的内容会在第一个空格处被截断(已使用utf-8编码为字节)。

输入文件text.txt内容

this is an input string

Python代码

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'')

我是否使用了错误的编码格式?子进程是一个使用fmt.Scanf监听输入的Go应用,代码如下:

Go子进程代码

package main

import "fmt"

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

    fmt.Println(inputs)
}

问题原因与解决方案

问题不是编码格式错误,而是Go代码中fmt.Scanf("%s", &inputs)的行为导致的:%s格式符会在遇到空白字符(空格、换行符等)时停止读取,因此只能获取到第一个空格前的内容。

解决方案1:使用bufio读取整行输入

修改Go代码,用bufio.Scanner读取完整的一行输入:

package main

import (
    "bufio"
    "os"
    "fmt"
)

func main() {
    scanner := bufio.NewScanner(os.Stdin)
    if scanner.Scan() {
        inputs := scanner.Text()
        fmt.Println(inputs)
    }
}

解决方案2:修改fmt.Scanf的格式符

将%s替换为%[^\n]s,表示读取直到换行符的所有内容(需额外处理换行符):

package main

import "fmt"

func main() {
    var inputs string
    fmt.Print("")
    // %[^\n]s 读取到换行符为止,末尾的\n用于消耗输入中的换行符
    fmt.Scanf("%[^\n]s\n", &inputs)

    fmt.Println(inputs)
}

内容的提问来源于stack exchange,提问作者Marty Farce

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.09 10:51:09