1

在 Python3.4 中,我使用以下代码使用 requests 库从网站打印 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()

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

4

1 回答 1

2

您可以让子进程从标准输入读取其输入并直接写入标准输入“文件”。

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
于 2016-03-17T12:29:30.000 回答