使用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
相关产品推荐
相关产品推荐

