我的代码是否因互联网连接问题而崩溃?如果是这样,我可以在尝试 api 之前制作一段代码来检查连接吗?

Is my code crashing because of internet connection issue? if so is there a way i can make a snippet of code to check connection before trying api?

我正在使用 Jupyter Notebook 运行 一个相当基本的加密货币交易机器人,在 coinbase 上有一个 API 并且在任意时间后,有时是 6 小时,有时是 18 小时,代码会出错并停止工作.. 是否有人遇到过此问题或能够从生成的错误脚本中确定问题。 错误代码如下..

    OSError                                   Traceback (most recent call last)
~\anaconda3\lib\site-packages\requests\packages\urllib3\connectionpool.py in urlopen(self, method, url, body, headers, retries, redirect, assert_same_host, timeout, pool_timeout, release_conn, chunked, body_pos, **response_kw)
    596             # Make the request on the httplib connection object.
--> 597             httplib_response = self._make_request(conn, method, url,
    598                                                   timeout=timeout_obj,

~\anaconda3\lib\site-packages\requests\packages\urllib3\connectionpool.py in _make_request(self, conn, method, url, timeout, chunked, **httplib_request_kw)
    385                     # otherwise it looks like a programming error was the cause.
--> 386                     six.raise_from(e, None)
    387         except (SocketTimeout, BaseSSLError, SocketError) as e:

~\anaconda3\lib\site-packages\requests\packages\urllib3\packages\six.py in raise_from(value, from_value)

~\anaconda3\lib\site-packages\requests\packages\urllib3\connectionpool.py in _make_request(self, conn, method, url, timeout, chunked, **httplib_request_kw)
    381                 try:
--> 382                     httplib_response = conn.getresponse()
    383                 except Exception as e:

~\anaconda3\lib\http\client.py in getresponse(self)
   1370             try:
-> 1371                 response.begin()
   1372             except ConnectionError:

~\anaconda3\lib\http\client.py in begin(self)
    318         while True:
--> 319             version, status, reason = self._read_status()
    320             if status != CONTINUE:

~\anaconda3\lib\http\client.py in _read_status(self)
    279     def _read_status(self):
--> 280         line = str(self.fp.readline(_MAXLINE + 1), "iso-8859-1")
    281         if len(line) > _MAXLINE:

~\anaconda3\lib\socket.py in readinto(self, b)
    703             try:
--> 704                 return self._sock.recv_into(b)
    705             except timeout:

~\anaconda3\lib\site-packages\requests\packages\urllib3\contrib\pyopenssl.py in recv_into(self, *args, **kwargs)
    292             else:
--> 293                 return self.recv_into(*args, **kwargs)
    294 

~\anaconda3\lib\site-packages\requests\packages\urllib3\contrib\pyopenssl.py in recv_into(self, *args, **kwargs)
    281             else:
--> 282                 raise SocketError(str(e))
    283         except OpenSSL.SSL.ZeroReturnError as e:

OSError: (10054, 'WSAECONNRESET')

During handling of the above exception, another exception occurred:

ProtocolError                             Traceback (most recent call last)
~\anaconda3\lib\site-packages\requests\adapters.py in send(self, request, stream, timeout, verify, cert, proxies)
    412             if not chunked:
--> 413                 resp = conn.urlopen(
    414                     method=request.method,

~\anaconda3\lib\site-packages\requests\packages\urllib3\connectionpool.py in urlopen(self, method, url, body, headers, retries, redirect, assert_same_host, timeout, pool_timeout, release_conn, chunked, body_pos, **response_kw)
    647 
--> 648             retries = retries.increment(method, url, error=e, _pool=self,
    649                                         _stacktrace=sys.exc_info()[2])

~\anaconda3\lib\site-packages\requests\packages\urllib3\util\retry.py in increment(self, method, url, response, error, _pool, _stacktrace)
    346             if read is False or not self._is_method_retryable(method):
--> 347                 raise six.reraise(type(error), error, _stacktrace)
    348             elif read is not None:

~\anaconda3\lib\site-packages\requests\packages\urllib3\packages\six.py in reraise(tp, value, tb)
    684         if value.__traceback__ is not tb:
--> 685             raise value.with_traceback(tb)
    686         raise value

~\anaconda3\lib\site-packages\requests\packages\urllib3\connectionpool.py in urlopen(self, method, url, body, headers, retries, redirect, assert_same_host, timeout, pool_timeout, release_conn, chunked, body_pos, **response_kw)
    596             # Make the request on the httplib connection object.
--> 597             httplib_response = self._make_request(conn, method, url,
    598                                                   timeout=timeout_obj,

~\anaconda3\lib\site-packages\requests\packages\urllib3\connectionpool.py in _make_request(self, conn, method, url, timeout, chunked, **httplib_request_kw)
    385                     # otherwise it looks like a programming error was the cause.
--> 386                     six.raise_from(e, None)
    387         except (SocketTimeout, BaseSSLError, SocketError) as e:

~\anaconda3\lib\site-packages\requests\packages\urllib3\packages\six.py in raise_from(value, from_value)

~\anaconda3\lib\site-packages\requests\packages\urllib3\connectionpool.py in _make_request(self, conn, method, url, timeout, chunked, **httplib_request_kw)
    381                 try:
--> 382                     httplib_response = conn.getresponse()
    383                 except Exception as e:

~\anaconda3\lib\http\client.py in getresponse(self)
   1370             try:
-> 1371                 response.begin()
   1372             except ConnectionError:

~\anaconda3\lib\http\client.py in begin(self)
    318         while True:
--> 319             version, status, reason = self._read_status()
    320             if status != CONTINUE:

~\anaconda3\lib\http\client.py in _read_status(self)
    279     def _read_status(self):
--> 280         line = str(self.fp.readline(_MAXLINE + 1), "iso-8859-1")
    281         if len(line) > _MAXLINE:

~\anaconda3\lib\socket.py in readinto(self, b)
    703             try:
--> 704                 return self._sock.recv_into(b)
    705             except timeout:

~\anaconda3\lib\site-packages\requests\packages\urllib3\contrib\pyopenssl.py in recv_into(self, *args, **kwargs)
    292             else:
--> 293                 return self.recv_into(*args, **kwargs)
    294 

~\anaconda3\lib\site-packages\requests\packages\urllib3\contrib\pyopenssl.py in recv_into(self, *args, **kwargs)
    281             else:
--> 282                 raise SocketError(str(e))
    283         except OpenSSL.SSL.ZeroReturnError as e:

ProtocolError: ('Connection aborted.', OSError("(10054, 'WSAECONNRESET')"))

During handling of the above exception, another exception occurred:

ConnectionError                           Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_26992/2760925491.py in <module>
     36 # dead zone
     37     if (price_diff < buy_diff) and (price_diff > sell_diff) and (wait_time<run_time):
---> 38         price_difference()
     39         wait_time = (run_time+180)
     40         run_log.logger.info("price difference in dead zone")

~\AppData\Local\Temp/ipykernel_26992/3172399590.py in price_difference()
     46     global difference
     47     global lastDiff
---> 48     price()
     49     historic_price()
     50     if current_price < hist_avg:

~\AppData\Local\Temp/ipykernel_26992/3172399590.py in price()
     23     global current_ask
     24     global last_price
---> 25     var=auth_client.get_product_order_book(trade_pair)
     26     bids=var.get('bids')
     27     asks=var.get('asks')

~\anaconda3\lib\site-packages\cbpro\public_client.py in get_product_order_book(self, product_id, level)
     86         """
     87         params = {'level': level}
---> 88         return self._send_message('get',
     89                                   '/products/{}/book'.format(product_id),
     90                                   params=params)

~\anaconda3\lib\site-packages\cbpro\public_client.py in _send_message(self, method, endpoint, params, data)
    266         """
    267         url = self.url + endpoint
--> 268         r = self.session.request(method, url, params=params, data=data,
    269                                  auth=self.auth, timeout=30)
    270         return r.json()

~\anaconda3\lib\site-packages\requests\sessions.py in request(self, method, url, params, data, headers, cookies, files, auth, timeout, allow_redirects, proxies, hooks, stream, verify, cert, json)
    486         }
    487         send_kwargs.update(settings)
--> 488         resp = self.send(prep, **send_kwargs)
    489 
    490         return resp

~\anaconda3\lib\site-packages\requests\sessions.py in send(self, request, **kwargs)
    607 
    608         # Send the request
--> 609         r = adapter.send(request, **kwargs)
    610 
    611         # Total elapsed time of the request (approximately)

~\anaconda3\lib\site-packages\requests\adapters.py in send(self, request, stream, timeout, verify, cert, proxies)
    471 
    472         except (ProtocolError, socket.error) as err:
--> 473             raise ConnectionError(err, request=request)
    474 
    475         except MaxRetryError as e:

ConnectionError: ('Connection aborted.', OSError("(10054, 'WSAECONNRESET')"))

我不知道它是否因为网络连接而崩溃。但是如果你想检查你是否有互联网连接,你可以 ping 一个服务器,例如 8.8.8.8 (Google DNS 服务器)。如果命令 returns 0 成功,如果 returns 1 失败。

import os
response_code = os.system("ping 8.8.8.8 -n 1")
print(response_code)

“连接重置”错误 通常 表示网络正常,但另一端的设备不正常,或者不想与您通话,尽管如此如今的“不洁”网络到处都是代理和防火墙,分层违规行为无处不在,可能还有更多奇特的原因。

无论如何,我不会尝试预测它(这将变得非常脆弱),而是在它发生时通过捕获异常来处理它。

所以它可能不是完美的解决方案,但在这种情况下它对我有用,有一个脚本只需重新启动主脚本 if/when 它崩溃了。

from subprocess import run
from time import sleep

# Path and name to the script you are trying to start
file_path = "CBPRO_BTC_USDC_V3.py" 
print('program started')
restart_timer = 60
def start_script():
    try:
        # Make sure 'python' command is available
        run("python "+file_path, check=True) 
    except:
        # Script crashed, lets restart it!
        handle_crash()

def handle_crash():
    print('Restarting in 60 seconds')
    sleep(restart_timer)  # Restarts the script after 60 seconds
    start_script()

start_script()