正确的方法来尝试/除了使用Python请求模块?

try: r = requests.get(url, params={'s': thing}) except requests.ConnectionError, e: print e #should I also sys.exit(1) after this? 

它是否正确? 有没有更好的方法来构造这个? 这将覆盖我所有的基地吗?

看看请求例外文档 。 简而言之:

如果发生networking问题(例如,DNS故障,拒绝连接等),请求将引发ConnectionErrorexception。

在罕见的HTTP响应无效的情况下,请求会引发HTTPErrorexception。

如果请求Timeout则会引发Timeoutexception。

如果请求超出configuration的最大redirect次数,则会引发TooManyRedirectsexception。

请求显式引发的所有exception都从requests.exceptions.RequestExceptioninheritance。

要回答你的问题,你所展示的不会涵盖你所有的基础。 你只会捕捉连接相关的错误,而不是超时。

当你发现exception时,怎么做才是真正的脚本/程序的devise。 退出是可以接受的吗? 你能继续下去吗? 如果错误是灾难性的,你不能继续下去,那么是的,对sys.exit()的调用是按顺序的。

您可以捕获基类exception,它将处理所有情况:

 try: r = requests.get(url, params={'s': thing}) except requests.exceptions.RequestException as e: # This is the correct syntax print e sys.exit(1) 

或者你可以分别抓住他们,做不同的事情。

 try: r = requests.get(url, params={'s': thing}) except requests.exceptions.Timeout: # Maybe set up for a retry, or continue in a retry loop except requests.exceptions.TooManyRedirects: # Tell the user their URL was bad and try a different one except requests.exceptions.RequestException as e: # catastrophic error. bail. print e sys.exit(1) 

正如基督徒指出的那样

如果你想要HTTP错误(例如401 Unauthorized)来引发exception,你可以调用Response.raise_for_status 。 如果响应是http错误,则会引发HTTPError

一个例子:

 try: r = requests.get('http://www.google.com/nothere') r.raise_for_status() except requests.exceptions.HTTPError as err: print err sys.exit(1) 

将打印:

 404 Client Error: Not Found for url: http://www.google.com/nothere 

一个额外的build议是明确的。 似乎最好从特定的一般到错误的堆栈,以获得所需的错误被捕获,所以具体的不被一般的掩盖。

 url='http://www.google.com/blahblah' try: r = requests.get(url,timeout=3) r.raise_for_status() except requests.exceptions.HTTPError as errh: print ("Http Error:",errh) except requests.exceptions.ConnectionError as errc: print ("Error Connecting:",errc) except requests.exceptions.Timeout: print ("Timeout Error:",errt) except requests.exceptions.RequestException as err: print ("OOps: Something Else",err) Http Error: 404 Client Error: Not Found for url: http://www.google.com/blahblah 

VS

 url='http://www.google.com/blahblah' try: r = requests.get(url,timeout=3) r.raise_for_status() except requests.exceptions.RequestException as err: print ("OOps: Something Else",err) except requests.exceptions.HTTPError as errh: print ("Http Error:",errh) except requests.exceptions.ConnectionError as errc: print ("Error Connecting:",errc) except requests.exceptions.Timeout: print ("Timeout Error:",errt) OOps: Something Else 404 Client Error: Not Found for url: http://www.google.com/blahblah