使用python从命令行下载文件

时间:2013-06-18 07:28:34

标签: python http download command-line-interface

我正在寻找一种通过HTTP下载文件的快速方法,使用命令行中的python one-liner(类似于wgetcurl的功能)。我们的想法是在Windows上启用快速复制/粘贴以下载distutils

我知道一种解决方案(请参阅下面的答案)。我对其他考虑以下因素的解决方案感兴趣:

  • 简明
  • 大多数“pythonic”解决方案
  • 兼容python2和python3
  • 跨平台
  • 可以有效处理大文件
  • 没有依赖关系(我们在这里提取distutils,我们不太可能在此阶段访问requests
  • 正确处理各种HTTP标头,例如Content-Disposition

2 个答案:

答案 0 :(得分:7)

我能提出的最简单的解决方案是:

try:
    from urllib.request import urlretrieve
except ImportError:
    from urllib import urlretrieve

urlretrieve('http://example.org', 'outfile.dat')

urlretrieve负责将资源下载到本地文件,并处理大文件。

但是忽略Content-Disposition标头,如果您想要考虑它,则需要使用urlopen并自行解析响应标头。 Content-Disposition不是HTTP标准头,所以我怀疑你会在python http库中找到它的支持......

答案 1 :(得分:5)

我的解决方案是:

python -c "import urllib; print urllib.urlopen('http://python-distribute.org/distribute_setup.py').read()" > distribute_setup.py