Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit a7e4b28

Browse files
committed
Support optional filename argument for retrieve() and urlretrieve(),
to specify where it should go (if specified, even local files will be copied into the given file).
1 parent 34e1777 commit a7e4b28

1 file changed

Lines changed: 12 additions & 8 deletions

File tree

Lib/urllib.py

Lines changed: 12 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -45,11 +45,14 @@ def urlopen(url):
4545
if not _urlopener:
4646
_urlopener = FancyURLopener()
4747
return _urlopener.open(url)
48-
def urlretrieve(url):
48+
def urlretrieve(url, filename=None):
4949
global _urlopener
5050
if not _urlopener:
5151
_urlopener = FancyURLopener()
52-
return _urlopener.retrieve(url)
52+
if filename:
53+
return _urlopener.retrieve(url, filename)
54+
else:
55+
return _urlopener.retrieve(url)
5356
def urlcleanup():
5457
if _urlopener:
5558
_urlopener.cleanup()
@@ -134,15 +137,15 @@ def open_unknown(self, fullurl):
134137
# External interface
135138
# retrieve(url) returns (filename, None) for a local object
136139
# or (tempfilename, headers) for a remote object
137-
def retrieve(self, url):
140+
def retrieve(self, url, filename=None):
138141
if self.tempcache and self.tempcache.has_key(url):
139142
return self.tempcache[url]
140143
url1 = unwrap(url)
141144
if self.tempcache and self.tempcache.has_key(url1):
142145
self.tempcache[url] = self.tempcache[url1]
143146
return self.tempcache[url1]
144147
type, url1 = splittype(url1)
145-
if not type or type == 'file':
148+
if not filename and (not type or type == 'file'):
146149
try:
147150
fp = self.open_local_file(url1)
148151
del fp
@@ -151,12 +154,13 @@ def retrieve(self, url):
151154
pass
152155
fp = self.open(url)
153156
headers = fp.info()
154-
import tempfile
155-
tfn = tempfile.mktemp()
156-
result = tfn, headers
157+
if not filename:
158+
import tempfile
159+
filename = tempfile.mktemp()
160+
result = filename, headers
157161
if self.tempcache is not None:
158162
self.tempcache[url] = result
159-
tfp = open(tfn, 'w')
163+
tfp = open(filename, 'w')
160164
bs = 1024*8
161165
block = fp.read(bs)
162166
while block:

0 commit comments

Comments
 (0)