2012-12-28 65 views
0

我從命令行執行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和文件renaqme到something.png

這可能

+1

檢查這個http://stackoverflow.com/questions/3979888/in-python-scipting-how-do-i-capture-output-from-subprocess-call-to-a-file – avasal

回答

3

如果你想要的是使用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) 
+0

我的圖像url是這樣的'image.php?u = 155594&dateline = 1182409179',我不知道它的擴展名是什麼。我可以找到與urllib – user19140477031

+0

該網址是一個重定向到真實圖像的網址?請檢查我更新的答案。 –

+0

我得到這個錯誤'輸入:無法打開X服務器'。我不知道有url重定向或不,但我打開瀏覽器中的鏈接,然後incan看到像'http://www.example.com/image.php?u = 155594&dateline = 1182409179'那裏的圖像顯示在瀏覽器中的圖像沒有在URL – user19140477031