在 Python 中重试连接之前暂停
我正在尝试连接到服务器。有时我无法连接到服务器,想暂停几秒钟再重试。我将如何在Python中实现暂停功能。这是我到目前为止所拥有的。谢谢。
while True:
try:
response = urllib.request.urlopen(http)
except URLError as e:
continue
break
我正在使用Python 3.2
I am trying to connect to a server. Sometimes I cannot reach the server and would like to pause for a few seconds before trying again. How would I implement the pause feature in Python. Here is what I have so far. Thank you.
while True:
try:
response = urllib.request.urlopen(http)
except URLError as e:
continue
break
I am using Python 3.2
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这会在继续之前阻塞线程 2 秒:
This will block the thread for 2 seconds before continuing:
如果您想并行运行大量这些,使用异步网络框架(例如 Twisted<)会更具可扩展性/a>,其中“睡眠”并不意味着阻止有价值且昂贵的操作系统线程执行其他一些有用的工作。下面是一个粗略的草图,说明如何可以根据需要并行尝试任意数量的请求(设置为 100),并设置超时(5 秒)、延迟(2 秒)和可配置的重试次数(此处为 10)。
In case you want to run lots of these in parallel, it would be much more scalable to use an asynchronous networking framework such as Twisted, where "sleeping" doesn't mean blocking a valuable and expensive OS thread from doing some other useful work. Here's a rough sketch of how you can attempt as many requests in parallel as you wish (set to 100), with timeout (5 seconds), delay (2 seconds) and a configurable number of retries (here, 10).