例外,所以当网络出现故障运行的功能

问题描述 投票:-1回答:2

我想知道,如何添加例外,以使程序运行和互联网时失败/下降运行功能:start()

Start()返回到开始和检查互联网存在。

我想补充这一点,因为有时当我的代码是在第56行(我删除了我的代码部分,因此它并不长)

互联网下降,我得到这个超时错误:

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()
python google-sheets-api gspread
2个回答
0
投票

你可以尝试类似如下:

while True:
    try:
        start()
    except Exception as e:
        print(str(e))
        time.sleep(10)

您可以过滤所需的异常,如果万一你不想共用例外。


0
投票

检查您的网络连接:

import requests

def is_connected():
    try:
        requests.get('http://216.58.192.142', timeout=1)
        return True
    except requests.exceptions.ConnectionError:
        return False
© www.soinside.com 2019 - 2024. All rights reserved.