我正在尝试使用python打印功能将输出写入管道,但无法弄清楚如何正确处理输出。这是我正在尝试的:
from subprocess import Popen, PIPE
pager = Popen("less", shell=True, bufsize=1, stdin=PIPE)
try:
print('1. Hey now!')
except Exception as e:
print(e)
try:
print('2. Hey now!', file=pager.stdin)
except Exception as e:
print(e)
try:
print('3. Hey now!'.encode('utf8'))
except Exception as e:
print(e)
try:
print('4. Hey now!'.encode('utf8'), file=pager.stdin)
except Exception as e:
print(e)
这是我在Python3.7中运行时得到的结果:
1. Hey now!
a bytes-like object is required, not 'str'
b'3. Hey now!'
a bytes-like object is required, not 'str'
每次我向管道写入数据时,它都会抱怨数据不是字节形式的,即使我将字节传递给print函数。如果我以二进制模式打开文件并将其文件描述符传递给print(),也会发生同样的事情。是否可以使用打印功能写入二进制流?如果是这样,我该怎么办?