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

使用Popen的communicate方法时遭遇TypeError错误求助

问题修复方案

错误原因

Python 3 中subprocess.Popen默认以字节流模式处理标准输入输出,当你通过communicate()传入字符串时,会触发类型错误——该方法需要字节类对象而非字符串。

修复方法

方法1:将字符串编码为字节

把要传入的command字符串编码成字节对象,再传给communicate():

def startRecording(channel, start, length, episode, show):
        tunerInstance = tuneChannel(channel)
        sched_cmd = ['at', '-t', start]
        command = 'ffmpeg -i /dev/ceton/ctn91xx_mpeg0_%s -c copy -t %s /mnt/primary-backup-drive/Backup/Recordings/%s-%s-%s.mp4' % (tunerInstance, length, show, episode, channel)
        p = Popen(sched_cmd, stdin=PIPE)
        p.communicate(command.encode('utf-8'))  # 编码为字节对象

方法2:启用文本模式

创建Popen实例时指定text=True(Python 3.3+支持),让标准输入输出以文本模式处理,直接传入字符串即可:

def startRecording(channel, start, length, episode, show):
        tunerInstance = tuneChannel(channel)
        sched_cmd = ['at', '-t', start]
        command = 'ffmpeg -i /dev/ceton/ctn91xx_mpeg0_%s -c copy -t %s /mnt/primary-backup-drive/Backup/Recordings/%s-%s-%s.mp4' % (tunerInstance, length, show, episode, channel)
        p = Popen(sched_cmd, stdin=PIPE, text=True)  # 启用文本模式
        p.communicate(command)

内容的提问来源于stack exchange,提问作者Richie Carnes

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 04:57:32