Python: Continue looping after exception

前端 未结 3 1905
野趣味
野趣味 2021-02-08 01:10

I have the following script (below). which will return the status code of URLs. It loops through a file and tries to connect to each host. Only problem is that it obviously stop

相关标签:
3条回答
  • 2021-02-08 01:25

    You could handle the exception where it is raised. Also, use a context manager when opening files, it makes for simpler code.

    with open(hostsFile, 'r') as f:
        for line in f:
            line = line.strip()
            if not line:
                continue
    
            epoch = str(time.time())
    
            try:
                conn = urllib.urlopen(line)
                print epoch + ": Connection successful, status code for " + line + " is " + str(conn.code) + "\n"
            except IOError:
                print epoch + ": Connection unsuccessful, unable to connect to server, potential routing issues\n"
    
    0 讨论(0)
  • 2021-02-08 01:34

    You need to handle exception raised by urllib.urlopen(line), something like this.

    try:
        f = file(hostsFile)
        while True:
            line = f.readline().strip()
            epoch = time.time()
            epoch = str(epoch)
            if len(line) == 0:
                break
            try:
               conn = urllib.urlopen(line)
            except IOError:
               print "Exception occured"
               pass
    except IOError:
        epoch = time.time()
        epoch = str(epoch)
        print epoch + ": Connection unsuccessful, unable to connect to server, potential routing issues\n"
        sys.exit()
    else:
        f.close()
    
    0 讨论(0)
  • 2021-02-08 01:38

    You could try catching the exception inside the while loop as something like this.

    try:
        f = file(hostsFile)
        while True:
            line = f.readline().strip()
            epoch = time.time()
            epoch = str(epoch)
            if len(line) == 0:
                break
            try:
                conn = urllib.urlopen(line)
                print epoch + ": Connection successful, status code for " + line + " is " + str(conn.code) + "\n"
            except:
                epoch = time.time()
                epoch = str(epoch)
                print epoch + ": Connection unsuccessful, unable to connect to server, potential routing issues\n"
    except IOError:
        pass
    else:
        f.close()
    
    0 讨论(0)
提交回复
热议问题