Python如何在5秒后继续循环

时间:2018-09-06 15:49:53

标签: python python-3.x python-2.7

import commands
    f = open("test.txt","r").readlines()    
    for l in f:
            x = l.strip()
            url = ("https://"+x+"/test")
            c = commands.getoutput("curl -I "+url)
            print (c)

执行代码时,代码在此行中花费很长时间[c = commands.getoutput(“ curl -I” + url)],我想设置一个时间,例如5秒。如果超过5秒,请移至循环9中的下一行)

1 个答案:

答案 0 :(得分:2)

您也可以使用requests代替curl来处理响应超时: http://docs.python-requests.org/en/master/user/quickstart/#timeouts。 像这样:

import requests
from requests.exceptions import Timeout

import commands

f = open("test.txt","r").readlines()    
for l in f:
    x = l.strip()
    url = ("https://"+x+"/test")
    try:
        response = requests.get(url, timeout=5)
    except Timeout:
        # do something
        continue