Python: Continue looping after exception

前端 未结 3 1955
野趣味
野趣味 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"
    

提交回复
热议问题