python 脚本没有输出

No output from python script

我想创建一段包含 2 个列表的代码(第一个是 IP 列表,第二个是端口列表)。使用迭代,我尝试实现连接(列表中的某些地址无法正常工作。)并获取第一个 HTTP 页面以检查地址是活的还是死的。

这是我写的代码:

import socket
import sys

ipees = []
portees = []

text_file = open("/home/loggyipport.txt", "r")
lines = text_file.readlines()

def go():
    for x in lines:
        ip, port = x.split()
        ipees.append(ip)
        portees.append(port)




go()

def dfunc(ipees, portees):
    for (ip, port) in zip(ipees, portees):
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        s.connect((ip, int(port)))
        s.send('GET / HTTP/1.0\r\n\r\n')
        while 1:
            buf = s.recv(1000)
        if not buf:
            break
        sys.stdout.write(buf)
        s.close()

dfunc(ipees, portees)

脚本 运行 没有错误。 问题是我没有输出。 有人能找出问题所在吗? 我使用 'zip' 函数的 for 循环是否正确编写?

您没有 return 函数内部的任何内容,也没有向控制台打印任何内容。你唯一一次这样做是在你有 sys.stdout.write(buf)dfunc(ipees, portees) 中。尝试添加一个 sys.stdout.flush 来刷新缓冲区并打印到屏幕。

sys.stdout.write(buf)
sys.stdout.flush()

实际上,我可能还发现了一个问题。脚本会终止吗? dfunc 中有一个无限的 while 循环。

while 1:
    buf = s.recv(1000)

我对 socket.socket 了解不多,但看起来那个循环永远不会终止。

你的

 if not buf:
     break

不属于您的循环。你必须修复它的缩进,所以它成为你循环的一部分。感谢 popovitsj 指出!

在您的 dfunc 函数中,程序成功连接到第一个 IP 并由于无限循环而无限等待来自服务器的数据。如果您只想检查是否从服务器接收到某些数据,则根本不需要 while 循环。

这里有一个函数可以满足您的需求:

def dfunc(ipees, portees):
    for (ip, port) in zip(ipees, portees):
        try:
            s = socket.create_connection((ip, port), timeout=10)
            s.send('GET / HTTP/1.0\r\n\r\n')
            buf = s.recv(1000)
            print buf
        except socket.error:
            print 'Could not connect to ({0}, {1})'.format(ip, port)