Python 3 urllib: 530 连接太多,在循环中

Python 3 urllib: 530 too many connections, in loop

我正在使用以下代码循环从 FTP 服务器检索数据文件:

   response = urllib.request.urlopen(url)
    data = response.read()
    response.close()
    compressed_file = io.BytesIO(data)
    gin = gzip.GzipFile(fileobj=compressed_file)

检索和处理前几个工作正常,但在几次请求后我收到以下错误:

    530 Maximum number of connections exceeded.

我尝试关闭连接(参见上面的代码)并使用 sleep() 计时器,但这两者都不起作用。我这里做错了什么?

可能是一个非常糟糕的解决方法,但这对我有用。我制作了一个脚本(此处称为 test.py)来执行请求(请参阅上面的代码)。下面的代码用于我提到的循环并调用 test.py

从子流程导入调用
以 open('log.txt', 'a') 作为 f: 调用(['python', 'test.py', args[0], args[1], stdout=f)

试图让 urllib 正确地做 FTP 会让我的大脑受伤。默认情况下,它为每个文件创建一个新连接,显然没有真正正确地确保连接关闭。 我觉得ftplib比较合适。

因为我碰巧正在处理与你(曾经)相同的数据...这是一个非常具体的答案,解压缩 .gz 文件并将它们传递到 ish_parserhttps://github.com/haydenth/ish_parser). 我觉得也够清楚了,可以作为一个笼统的回答。

import ftplib
import io
import gzip
import ish_parser # from: https://github.com/haydenth/ish_parser

ftp_host = "ftp.ncdc.noaa.gov"
parser = ish_parser.ish_parser()

# identifies what data to get
USAF_ID = '722950'
WBAN_ID = '23174'
YEARS = range(1975, 1980)

with ftplib.FTP(host=ftp_host) as ftpconn:
    ftpconn.login()

    for year in YEARS:
        ftp_file = "pub/data/noaa/{YEAR}/{USAF}-{WBAN}-{YEAR}.gz".format(USAF=USAF_ID, WBAN=WBAN_ID, YEAR=year)
        print(ftp_file)

        # read the whole file and save it to a BytesIO (stream)
        response = io.BytesIO()
        try:
            ftpconn.retrbinary('RETR '+ftp_file, response.write)
        except ftplib.error_perm as err:
            if str(err).startswith('550 '):
                print('ERROR:', err)
            else:
                raise

        # decompress and parse each line 
        response.seek(0) # jump back to the beginning of the stream
        with gzip.open(response, mode='rb') as gzstream:
            for line in gzstream:
                parser.loads(line.decode('latin-1'))

这确实会将整个文件读入内存,这可能可以使用一些聪明的包装器 and/or yield 或其他东西来避免......但是对于一年的每小时天气观测值来说效果很好。