且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用什么命令代替 urllib.request.urlretrieve?

更新时间:2022-10-20 15:43:59

已弃用 是一回事,将来可能会被弃用 是另一回事.>

如果它适合您的需求,我会继续使用 urlretrieve.

也就是说,你可以不用它:

from urllib.request import urlopen从shutil 导入copyfileobj使用 urlopen(my_url) 作为 in_stream,open('my_filename', 'wb') 作为 out_file:copyfileobj(in_stream, out_file)

I'm currently writing a script that downloads a file from a URL

import urllib.request
urllib.request.urlretrieve(my_url, 'my_filename')

According to the docs, urllib.request.urlretrieve is a legacy interface and might become deprecated, therefore I would like to avoid it so I don't have to rewrite this code in the near future.

I'm unable to find another interface like download(url, filename) in standard libraries. If urlretrieve is considered a legacy interface in Python 3, what is the replacement?

Deprecated is one thing, might become deprecated at some point in the future is another.

If it suits your needs, I'd continuing using urlretrieve.

That said, you can do without it:

from urllib.request import urlopen
from shutil import copyfileobj

with urlopen(my_url) as in_stream, open('my_filename', 'wb') as out_file:
    copyfileobj(in_stream, out_file)