我想知道如何添加异常,以便当程序运行且Internet失败/丢失时运行功能:start()
。
Start()
循环回到开头,并检查是否存在Internet。
我想添加此代码是因为有时当我的代码在第56行时(我删除了部分代码,所以它并不那么长)
Internet断开,并且出现此超时错误:
requests.exceptions.ConnectionError: ('Connection aborted.', TimeoutError(10060, 'A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond', None, 10060, None))
我正在运行以下代码:
def start():
import socket, time, os
def is_connected():
try:
# check if internet is present by connecting to google
socket.create_connection(("www.google.com", 80))
return True
except OSError:
pass
return False
if is_connected() == True:
print("Internet connected!")
def main():
import gspread, random, subprocess
from oauth2client.service_account import ServiceAccountCredentials
import numpy as np
from PIL import Image, ImageFont, ImageDraw
'''
Setup Gspread API
'''
scope = ['https://spreadsheets.google.com/feeds', 'https://www.googleapis.com/auth/drive']
creds = ServiceAccountCredentials.from_json_keyfile_name('client_secret.json', scope)
client = gspread.authorize(creds)
sheet = client.open('xxxx').sheet1
def findEmployee():
'''
Find database lenght
'''
totDatabaseLenght = sheet.col_values(1)
databaseLenght = len(totDatabaseLenght)
'''
Loop so it runs trugh all employees
'''
count = 2
countClock = databaseLenght +1 #Otherwise the program misses the last row
while count < countClock:
'''
Update database lenght
'''
totDatabaseLenght = sheet.col_values(1)
databaseLenght = len(totDatabaseLenght)
#print("Update database lenght")
'''
Find photo url of selected employee
'''
SelectedCell = sheet.cell(count, 1).value
photoUrl = "D:\\Bureaublad\\xx\\PhotoDatabase\\original\\" + SelectedCell + ".jpg"
'''
Check if employee's photo is available
'''
fileCheck = os.path.isfile(photoUrl)
if fileCheck == True:
#print("File Exists")
###DELETED SOME OF MY CODE SO IT IS SHORTER###
print(SelectedCell, "Completed")
sheet.update_cell(count,7, '')
count = count + 1
time.sleep(1)
else:
#print("File Does not exist")
print(SelectedCell, "PhotoNotFound")
sheet.update_cell(count,7, SelectedCell)
count = count + 1
time.sleep(1)
'''
Run findEmployee
'''
findEmployee()
#Infinite loop
clock = 0
while True:
clock = clock +1
print("Program has run:", clock, "times!")
main()
elif is_connected() == False:
print("No internet connection!")
time.sleep(20)
start()
else:
print("Error")
time.sleep(20)
start()
start()
答案 0 :(得分:0)
检查您的互联网连接:
import requests
def is_connected():
try:
requests.get('http://216.58.192.142', timeout=1)
return True
except requests.exceptions.ConnectionError:
return False
答案 1 :(得分:0)
您可以尝试以下方法吗?
while True:
try:
start()
except Exception as e:
print(str(e))
time.sleep(10)
如果您不希望常见异常,则可以过滤所需的异常。