对于x中的i:关于循环列表的问题

时间:2019-01-28 16:12:25

标签: python-3.x

下面是我要运行的代码,但是,我不确定如何使列表中的每个项目循环执行。 寻找一些建议

import socket
import time
sock = sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
testinput = input('''Please enter the number corrosponding to the test you would like to carry out 
                1. HTTP Test to Horizon 
    Choice: ''')
if testinput == '1':
    print('You have choosen test 1')
    print('Test port 80 to xsi.unlimitedhorizon.co.uk...')
    for i in ['88.215.60.155', '88.215.60.156', '88.215.60.166', '88.215.60.168']:
        port80result = sock.connect_ex((i, 80))
        if port80result == 0:
            print('Test Successful for ' + i)

运行此命令,我想进行套接字测试,测试列表中的每个IP地址。 但是我只得到以下内容,然后结束:

    Please enter the number corresponding to the test you would like to carry out                1. HTTP Test to Horizon
    Choice: 1
You have chosen test 1
Test port 80 to xsi.unlimitedhorizon.co.uk...
Test Successful for 88.215.60.155

如您所知,我的学习曲线仍然很陡

感谢任何人的帮助:)

1 个答案:

答案 0 :(得分:0)

感谢您的答复。我已经能够解决这个问题。 -增加了套接字超时 -添加了其他:如果测试失败

下面的更新代码:

import socket
import time

sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.settimeout(2)
testinput = input('''Please enter the number corrosponding to the test you would like to carry out 
                1. HTTP Test to Horizon 
    Choice: ''')
if testinput == '1':
    print('You have choosen test 1')
    print('Test port 80 to xsi.unlimitedhorizon.co.uk...')
    for i in ['88.215.60.155', '88.215.60.156', '88.215.60.166', '88.215.60.168']:
        port80result = sock.connect_ex((i, 80))
        socket.timeout(1)
        if port80result == 10061:
            print('Test Successful for ' + i)
        else:
            print(port80result)