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.get(url, stream=True)
i = img.raw.read()
proc = subprocess.Popen(['icat', '-'], stdout=PIPE, stdin=PIPE, stderr=STDOUT)
proc.communicate(i)
#proc.stdin.write(i) # I tried this too

Unfortunately, the subprocess does nothing, and I get no errors. What is wrong with my code, and is there a cross-platform solution?


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;15mx1b[48;5;15m'
链接地址: http://www.djcxy.com/p/77094.html

上一篇: 未知参数:

下一篇: Python:管道请求图像参数为stdin