【问题标题】:How to grab the output from python subprocess如何从python子进程中获取输出
【发布时间】:2012-12-28 06:45:05
【问题描述】:

我正在使用这个从命令行执行 python 脚本

python myscript.py

这是我的脚本

if item['image_urls']:
            for image_url in item['image_urls']:
            subprocess.call(['wget','-nH', image_url, '-P  images/'])

现在当我在屏幕上运行时,我会看到这样的输出

HTTP request sent, awaiting response... 200 OK
Length: 4159 (4.1K) [image/png]

现在我想要的是终端上不应该有输出。

我想获取输出并从那里找到图像扩展名,即从[image/png] 获取png 并将文件重新命名为something.png

这可能吗

【问题讨论】:

标签: python linux subprocess wget


【解决方案1】:

如果您只想使用wget 下载东西,何不试试标准python 库中的urllib.urlretrieve

import os
import urllib
image_url = "https://www.google.com/images/srpr/logo3w.png"
image_filename = os.path.basename(image_url)
urllib.urlretrieve(image_url, image_filename)

编辑:如果图片是通过脚本动态重定向的,你可以试试requests包来处理重定向。

import requests
r = requests.get(image_url)
# here r.url will return the redirected true image url
image_filename = os.path.basename(r.url)
f = open(image_filename, 'wb')
f.write(r.content)
f.close()

我没有测试代码,因为我没有找到合适的测试用例。 requests 的一大优势是它还可以处理 authorization

EDIT2:如果图像是由脚本动态提供的,例如gravatar 图像,您通常可以在响应头的content-disposition 字段中找到文件名。

import urllib2
url = "http://www.gravatar.com/avatar/92fb4563ddc5ceeaa8b19b60a7a172f4"
req = urllib2.Request(url)
r = urllib2.urlopen(req)
# you can check the returned header and find where the filename is loacated
print r.headers.dict
s = r.headers.getheader('content-disposition')
# just parse the filename
filename = s[s.index('"')+1:s.rindex('"')]
f = open(filename, 'wb')
f.write(r.read())
f.close()

EDIT3:正如@Alex 在评论中建议的那样,您可能需要在返回的标头中清理编码的filename,我认为只需获取基本名称即可。

import os
# this will remove the dir path in the filename
# so that `../../../etc/passwd` will become `passwd`
filename = os.path.basename(filename)

【讨论】:

  • 我的图片网址是这样的image.php?u=155594&dateline=1182409179,我不知道它的扩展名是什么。我可以用 urllib 找到吗
  • 这个url是重定向到真实图片的url吗?请检查我更新的答案。
  • 我收到此错误import: unable to open X server 。我不知道是否存在 url 重定向,但我在浏览器中打开该链接然后可以看到那里的图像,如 http://www.example.com/image.php?u=155594&dateline=1182409179 在浏览器中显示图像,而 url 中没有任何变化
  • 确保filename 不是恶意的 - 使用secure_filename() 之类的东西来防止../../../etc/passwd
猜你喜欢
  • 2020-03-03
  • 1970-01-01
  • 2015-01-21
  • 2015-06-08
  • 2021-01-18
  • 2011-09-08
  • 1970-01-01
  • 2020-05-03
  • 1970-01-01
相关资源
最近更新 更多