In Python3.4 I am using the following code to print a PDF from a website using the requests library:
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()
Is there a way to skip the temporary file save and stream directly the printer directly?
You can have the subprocess read its input from stdin and write to the stdin "file" directly.
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