[Tutor] Download file from the web and store it locally.

S. D. Rose s_david_rose at hotmail.com
Wed May 24 18:19:36 CEST 2006


Matt- Have you tried running this line-by-line in IDLE?  I've done a script 
almost exactly the same as what you're doing ( I downloaded a .jpg file from 
a web-server ), and when I was trying to learn what commands did what, I 
quickly changed from trying to write a 'program' to running lines 
individually in IDLE so I could print out the results of each command, and 
to see exactly what lines 'work', which have syntax errors and which have 
logic errors.

People often want a compiler which spits out executables, but I realized 
it's nice to be able to type a few lines of an algorithm into the 
interpreter and see the results, so I can see if I get the results I expect, 
then copy that and paste it into my 'program'.

-Dave

Now, for wxPython (a windowing superset of python), my routine was:

---SNIP---
WebImage = urllib2.urlopen("%s/jpg/fullsize.jpg" %netCamAddress)
rawJpg = WebImage.read()
photostream = cStringIO.StringIO(rawJpg)
photoJpg = wx.ImageFromStream(photostream)
photoBmp = wxBitmapFromImage(photoJpg)
liveVideo.SetBitmap(photoBmp)
---SNIP---

"Give a man a fish; you have fed him for today.  Teach a man to fish; and 
you have fed him for a lifetime.  Show a man what a fish looks like so he 
doesn't try to eat a tire he fishes out of the pond."

So, let me show you what a "fish" looks like.  I expect the first two lines 
are of use to you, where the bottom-four lines are specific to wxPython. 
Realize what is happening with the string in the first line?  I'm replacing 
part of the web-address with the contents of the variable netCamAddress. 
Can you figure out how that is working? hint- you can try printing 
"%s/jpg/fullsize.jpg" %netCamAddress directly in IDLE after setting 
netCamAddress to a string value to see what the result is, so you know what 
urllib2 is opening ....

After line two is executed, the contents of rawJpg is the .jpg file I 
downloaded.  Do you know what to do next?  Maybe open a file in binary mode, 
and write rawJpg' to the file then close it?

Also, do you realize I'm using a different library for urlopen than you 
used?  Do you know which one, and how to import it?

Lastly, there are a couple ways you can specify your file in python.

"D:\\Temp\\file"
but I like using raw strings.
r"d:\directory\file.ext"
(I hate double-slashing.  It's so visually messy, it makes it easy to miss 
things like commas I think...)

http://docs.python.org/tut/node9.html#SECTION009200000000000000000
Maybe sections 7.2 and 7.2.1 are relevent to the rest of your goals?

-Dave 





More information about the Tutor mailing list