我有这个Twitter应用程序,我在本地运行它有时它失败,因为慢速互联网连接。一旦失败,我必须从Cmd重新启动应用程序。如果网络出现故障并重试代码
,是否可以使机器人进入睡眠状态import tweepy, time, sys
argfile = str(sys.argv[1])
#APP
#CONSUMER_KEY = '11'
#CONSUMER_SECRET = '11'
#ACCESS_KEY = '11'
#ACCESS_SECRET = '11'
auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)
auth.set_access_token(ACCESS_KEY, ACCESS_SECRET)
api = tweepy.API(auth)
filename=open(argfile,'r')
f=filename.readlines()
filename.close()
for line in f:
api.update_status(line)
time.sleep(1200)
答案 0 :(得分:0)
我会做这样的事情:
import requests
import socket
def get_json(url):
"""Fetches JSON response from specified URL"""
fetched_data = dict()
try:
request = requests.get(url, timeout=2)
try:
fetched_data = request.json()
print("JSON response data:")
print(fetched_data)
except ValueError:
fetched_data["status"] = "60"
except requests.ConnectionError:
fetched_data["status"] = "60"
except requests.Timeout:
fetched_data["status"] = "60"
except requests.HTTPError:
fetched_data["status"] = "60"
except requests.URLRequired:
fetched_data["status"] = "60"
except requests.TooManyRedirects:
fetched_data["status"] = "60"
except socket.timeout:
fetched_data["status"] = "60"
return data
稍后,我会将它包裹在一些while循环中,检查状态,如果状态为60,我会让它进入睡眠状态,否则按照你想要的那样。