httpサーバーからhdf5ファイルをダウンロードしようとしています。Pythonサブプロセスモジュールとwgetでこれを行うことができますが、浮気しているように感じます
# wget solution
import subprocess
url = 'http://url/to/file.h5'
subprocess(['wget', '--proxy=off', url])
urllibとrequestモジュールを使用して、次のような画像をダウンロードすることもできます。
# requests solution
url2 = 'http://url/to/image.png'
r = requests.get(url2)
with open('image.png', 'wb') as img:
img.write(r.content)
# urllib solution
urllib.urlretrieve(url2, 'outfile.png')
ただし、このメソッドを使用してhdf5-fileをダウンロードし、シェルコマンド'file'を実行しようとすると、次のようになります。
>file test.h5
>test.h5: HTML document, ASCII text, with very long lines
これがrequests.get()のヘッダーです(役立つかどうかはわかりません)
{'accept-ranges': 'bytes',
'content-length': '413399',
'date': 'Tue, 19 Feb 2013 08:51:06 GMT',
'etag': 'W/"413399-1361177055000"',
'last-modified': 'Mon, 18 Feb 2013 08:44:15 GMT',
'server': 'Apache-Coyote/1.1'}
wget througサブプロセスを使用する必要がありますか、それともpythonicソリューションがありますか?
解決策: この問題は、ファイルをダウンロードしようとする前にプロキシを無効にしなかったために、転送が傍受されたことが原因でした。このコードがうまくいきました。
import urllib2
proxy_handler = urllib2.ProxyHandler({})
opener = urllib2.build_opener(proxy_handler)
urllib2.install_opener(opener)
url = 'http://url/to/file.h5'
req = urllib2.Request(url)
r = opener.open(req)
result = r.read()
with open('my_file.h5', 'wb') as f:
f.write(result)