Reputation: 3
learning python there. I want to write a script to check if my webserver has picture named in the root 123.jpg
I have:
import urllib2
numeruks=100
adresiuks="http://localhost/" + str(numeruks) +".jpg"
try:
if numeruks < 150:
numeruks = numeruks + 1
urllib2.urlopen(adresiuks).read()
reading manuals all day, can't solve it :(
Upvotes: 0
Views: 222
Reputation: 1
After you increment numeruks you should reset the adresiuks.
I.E.:
adresiuks="http://localhost/" + str(numeruks) + ".jpg"
try:
if numeruks < 150:
numeruks = numeruks + 1
adresiuks = "http://localhost/" + str(numeruks) + ".jpg"
print adresiuks
urllib2.urlopen(adresiuks).read()
Double check the file is available using your web browser.
For example my web server is listening on port 8000 so I have to add the port, i.e.
http://localhost:8000/123.jpg
.
Here is a simple running script, because it is a .jpg it will be garbage that is printed:
import urllib2
numeruks = 123
adresiuks = "http://localhost/" + str(numeruks) + ".jpg"
print adresiuks
thefile = urllib2.urlopen(adresiuks).read()
print thefile
Upvotes: 0
Reputation: 96
Is this code standing on its own? If so, you're missing a loop. Also, as codeape said, the indentation is wrong and you need an except
or a finally
.
If you want to check all of the numbers between 100 and 150, you'll need to loop over them. Your code as it stands now only updates numeruks
once, and never updates adresiuks
at all. If you want to check for an error with a try
, you need to follow it up with an except
, which can be as simple as pass
(but will more likely be continue
).
I'm a little hesitant to give you the actual code, as if you're learning, you'll probably learn it better if you figure it out yourself. ;)
Upvotes: 1
Reputation: 97962
You can test for 404 in your attempts to access the URL (and without even having to issue a read()
):
import urllib2
n = 123
try:
url = 'http://localhost/%d.jpg' % n
urllib2.urlopen(url)
except urllib2.HTTPError, e:
if e.code == 404:
print '%d.jpg was not found' % n
else:
raise # if the issue wasn't a 404, then re-raise the exception
Upvotes: 1