Python: Piping Requests Image Argument To Stdin
I am trying to send arguments to a subprocess' stdin. In my case, it is an image downloaded with Requsts. Here is my code: from subprocess import Popen, PIPE, STDOUT img = requests
Solution 1:
icat
queries your terminal to see what dimensions to resize the image to, but a pipe is not suitable as a terminal and you end up with empty output. The help information from icat
states:
Big images are automatically resized to your terminal width, unless with the -k option.
When you use the -k
switch output is produced.
There is no need to stream here, you can just leave the loading to requests
and pass in the response body, un-decoded:
img = requests.get(url)
proc = subprocess.Popen(['icat', '-k', '-'], stdout=PIPE, stdin=PIPE, stderr=STDOUT)
stdout, stderr = proc.communicate(img.content)
The stderr
value will be empty, but stdout
should contain transformed image data (ANSI colour escapes):
>>> import requests
>>> import subprocess
>>> url = 'https://www.gravatar.com/avatar/24780fb6df85a943c7aea0402c843737'
>>> img = requests.get(url)
>>> from subprocess import PIPE, STDOUT
>>> proc = subprocess.Popen(['icat', '-k', '-'], stdout=PIPE, stdin=PIPE, stderr=STDOUT)
>>> stdout, stderr = proc.communicate(img.content)
>>> len(stdout)
77239
>>> stdout[:20]
'\x1b[38;5;15m\x1b[48;5;15m'
Post a Comment for "Python: Piping Requests Image Argument To Stdin"