3

I want to check what HTTP status code is returned for an HTTP(S) URL. I don't care about content, so I just request head with curl -I $url or curl --head $url

But what's the exit code I should check for, e.g. in subprocess.check_call? In particular, do I get a non-zero exit code for HTTP 403?

5

curl -I will always return 0, if it managed to produce an output with the HEAD. You have two alternatives.

The first is to use curl -I --fail instead, and check for exit code 22.

If you're doing this in a Python script, it could look like:

try:
    subprocess.check_call(['curl', '-I', '--fail', url])
except subprocess.CalledProcessError as e:
    if e.returncode == 22:
        (do something)

The second is to actually ask just the HTTP status code, like this:

$ curl -s -I -o /dev/null -w '%{http_code}' $bad-url
403
1

If you truly just want the HTTP status codes from a python script, you may want to check out the 'requests' library:
http://docs.python-requests.org/en/latest/

#Prints status code:
import requests r = requests.get('http://superuser.com') print(r.status_code)

  • True, though the question was about curl only for other reasons. – Nemo May 13 '15 at 10:40

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.