【问题标题】:What is the pythonic way of downloading hdf5 files from http server?从http服务器下载hdf5文件的pythonic方式是什么?
【发布时间】:2013-02-03 21:38:28
【问题描述】:

我正在尝试从 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 子进程还是有 python 解决方案?

解决方案: 问题是由于我在尝试下载文件之前没有禁用代理,因此传输被拦截。这段代码成功了。

    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)

【问题讨论】:

  • 有了urllib,你真的看过文件了吗?听起来更像是请求被拦截,并且您正在下载 html 文档而不是您正在寻找的 png。所以也许你能找到更好的链接?
  • 你是对的,请求被拦截了!当我禁用代理并做其他事情时,我终于得到了正确的文件。这是我在 SO 上的第一篇文章。可以包含我对原始问题的完整解决方案吗?我应该以某种方式编辑问题的标题吗?
  • 是的,您也可以编辑您的问题,然后发布您的答案。

标签: python urllib hdf5


【解决方案1】:

尝试使用 urllib.geturl 获取真实 URL(在重定向之后),然后将其传递给 urlretrieve

【讨论】:

    猜你喜欢
    • 2012-06-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-23
    • 2011-06-03
    • 1970-01-01
    相关资源
    最近更新 更多