从 Web 打印 PDF 而无需先保存到文件系统

Print PDF from web without saving to filesystem first

在 Python3.4 中,我使用以下代码从使用请求库的网站打印 PDF:

with open(temp_pdf_file, 'wb') as handle:
   response = requests.get(html.unescape(message['body']), stream=True)
   for block in response.iter_content(1024):
       handle.write(block)
cmd = '/usr/bin/lpr -P {} {}'.format(self.printer_name,temp_pdf_file)
print(cmd)
proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
stdout, stderr = proc.communicate()
exit_code = proc.wait()

有没有办法跳过临时文件保存,直接流式传输到打印机?

您可以让子进程从标准输入读取其输入并直接写入标准输入"file"。

import requests
from subprocess import Popen, PIPE

message = ...

cmd = '/usr/bin/lpr -P {}'.format(self.printer_name)
proc = Popen(cmd, stdin=PIPE, stdout=PIPE, stderr=PIPE, shell=True)
response = requests.get(html.unescape(message['body']), stream=True)
for block in response.iter_content(1024):
    proc.stdin.write(block)
stdout, stderr = proc.communicate()
exit_code = proc.wait()
print exit_code