Python: piping Requests image argument to stdin

我的未来我决定 提交于 2019-12-12 02:14:08

问题


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?


回答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'


来源:https://stackoverflow.com/questions/26980469/python-piping-requests-image-argument-to-stdin

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!