使用python从命令行下载文件

dwu*_*urf 6 python http download command-line-interface

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

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

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

mat*_*ata 7

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

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

urlretrieve('http://example.org', 'outfile.dat')
Run Code Online (Sandbox Code Playgroud)

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

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

  • Python 3: `python3 -c "from urllib.request import urlretrieve; urlretrieve('http://python-distribute.org/distribute_setup.py', 'distribute_setup.py')"` (5认同)
  • Python 2:来自urllib import urlretrieve的`python -c"; urlretrieve('http://python-distribute.org/distribute_setup.py','distribute_setup.py')"` (4认同)
  • Dwurf的答案是正确的:最初的问题是希望将其作为适合直接从命令行调用的单行代码。(巧合的是,寻找使我来到了这里)。 (2认同)

dwu*_*urf 6

我的解决方案是:

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