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

时间:2016-03-17 00:10:51

标签: python python-3.x pdf printing lpr

在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()

有没有办法直接跳过临时文件保存并直接流式打印?

1 个答案:

答案 0 :(得分:2)

您可以让子进程从stdin读取其输入并直接写入stdin“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