Python3 TypeError:期望字符串参数却获bytes的问题排查与解决
问题原因与解决方法
为什么会报错?
- Python 3 里
subprocess.check_output()执行命令后,默认返回字节流(bytes类型)。 - 你用的
StringIO()是专门用来操作**文本字符串(str类型)**的工具,把字节流直接传给它的write()方法,就会触发TypeError: string argument expected, got 'bytes'。 - 你注释掉的
StringIO.StringIO()是 Python 2 的写法,Python 2 里它兼容字节处理,但 Python 3 把字符串和字节流的处理拆分成了StringIO(管文本)和BytesIO(管二进制)两个类。
解决办法(推荐方案)
直接用 BytesIO 替代 StringIO 来处理二进制的图片数据,修改代码如下:
import subprocess from io import BytesIO # 替换原来的StringIO导入 from PIL import Image # 补充你代码中用到但未声明的Image导入 def captureTestImage(settings, width, height): command = "raspistill %s -w %s -h %s -t 200 -e bmp -n -o -" % (settings, width, height) imageData = BytesIO() # subprocess返回的bytes可以直接写入BytesIO imageData.write(subprocess.check_output(command, shell=True)) imageData.seek(0) # 指针移回开头,让Image.open能读取 im = Image.open(imageData) buffer = im.load() imageData.close() return im, buffer # 调用部分无需修改 image1, buffer1 = captureTestImage(str(cameraSettings), str(testWidth), str(testHeight))
为什么你之前强制转换没用?
如果只是简单把 bytes 转成 str(比如 str(subprocess.check_output(...))),得到的是带 b'' 标识的字符串(比如 b'\x42\x4D...'),这不是原始的二进制图片数据,Image.open 根本识别不了,所以解决不了问题。
内容的提问来源于stack exchange,提问作者Jshee
相关产品推荐
相关产品推荐

