tags:

views:

78

answers:

3

Hello, 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 :(

+2  A: 

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
Jarret Hardie
Should also check 200 before throwing an exception.
Jay Zeng
Good thinking Jay, though a 200 response won't raise an HTTPError in the first place.
Jarret Hardie
+1  A: 

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. ;)

Robotica
A: 

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
over.itches