Discuss / Python / 功能废弃等问题

功能废弃等问题

Topic source

sq

#1 Created at ... [Delete] [Delete and Lock User]

这里的代码其实基本都已经废弃了,其实可以直接跳过的,看后面就行了

Cao Yi

#2 Created at ... [Delete] [Delete and Lock User]

后面一章提了一部分,但是Python更新的版本还有一些变化。

Cao Yi

#3 Created at ... [Delete] [Delete and Lock User]

如果要在 Python 3.11 里运行,网络连接来获取sina、sohu和163的网站首页的代码可以改成如下:

import asyncio


async def wget(host):
    print('wget %s...' % host)
    connect = asyncio.open_connection(host, 80)
    reader, writer = await connect
    header = 'GET / HTTP/1.0\r\nHost: %s\r\n\r\n' % host
    writer.write(header.encode('utf-8'))
    await writer.drain()
    while True:
        line = await reader.readline()
        if line == b'\r\n':
            break
        print('%s header > %s' % (host, line.decode('utf-8').rstrip()))
    # Ignore the body, close the socket
    writer.close()

loop = asyncio.get_event_loop()
tasks = [wget(host)
         for host in ['www.sina.com.cn', 'www.sohu.com', 'www.163.com']]
loop.run_until_complete(asyncio.gather(*tasks))
loop.close()

注意,除了使用下节提到的 async/await, 如果 tasks 是一个 list,调用时,需用 

asyncio.gather(*tasks)

  • 1

Reply