今天遇到一个问题,想把python存储在内存里的一段音频直接通过pipe输出到ffmpeg进行转码。因为对pipe的获取了解的不多,所以决定输出到stdout再用交互shell的|
符号交给ffmpeg。这就涉及到了stdout的二进制输出。
百度了好久,发现基本所有的文章都是基于python 2的,而且都是抄的同一篇文章…就不吐槽了,解决还得靠自己。
首先,print函数肯定不能用,因为print会自动调用__str__
转换为字符串格式,而一转换肯定没法原始字节流输出…注意到print
的参数里面有一个可选参数是file
,默认值是sys.stdout
(a file-like object (stream); defaults to the current sys.stdout.),那就试一下直接调用sys.stdout
的write
方法。
不料…
Python 3.10.4 | packaged by conda-forge | (main, Mar 24 2022, 17:32:50) [MSC v.1929 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys
>>> sys.stdout.write(b'test')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: write() argument must be str, not bytes
没办法,只能输出字符串…但接下来的探索受到了这篇文章的启发,于是尝试直接写入stdout的缓冲区:
>>> type(sys.stdout.buffer)
<class '_io.BufferedWriter'>
>>> sys.stdout.buffer.write(b'test')
test4
>>> sys.stdout.buffer.write(b'\xe6\xb5\x8b\xe8\xaf\x95')
测试6
成功!