我正在尝试从 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 文件并运行 shell 命令“文件”时,我得到:
>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)