当不是 HTTP 200 时,“curl -I”的退出代码是什么?

Nem*_*emo 3 html python curl exit-code http-status-codes

我想检查为 HTTP(S) URL 返回的 HTTP 状态代码。我不在乎内容,所以我只用 curl -I $url 或 curl --head $url 请求 head

但是我应该检查的退出代码是什么,例如在subprocess.check_call 中?特别是,我是否会获得 HTTP 403 的非零退出代码?

Nem*_*emo 5

curl -I将始终返回0,如果它设法用 HEAD 产生输出。你有两个选择。

第一种是使用curl -I --fail 替代,并检查是否有退出代码22

如果您在 Python 脚本中执行此操作,它可能如下所示:

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

第二个是实际上只询问 HTTP 状态代码,如下所示:

$ curl -s -I -o /dev/null -w '%{http_code}' $bad-url
403
Run Code Online (Sandbox Code Playgroud)