MST

星途 面试题库

面试题:Python网络编程并发之多线程应用

在Python网络编程中,使用多线程模块`threading`实现一个简单的并发网络请求示例,要求至少请求两个不同的URL,并处理可能出现的异常,最后输出每个请求的响应状态码。
39.5万 热度难度
编程语言Python

知识考点

AI 面试

面试题答案

一键面试
import threading
import requests


def fetch_url(url):
    try:
        response = requests.get(url)
        print(f"URL: {url}, Status Code: {response.status_code}")
    except requests.RequestException as e:
        print(f"Error fetching {url}: {e}")


if __name__ == "__main__":
    urls = [
        'https://www.example.com',
        'https://www.github.com'
    ]
    threads = []
    for url in urls:
        thread = threading.Thread(target=fetch_url, args=(url,))
        threads.append(thread)
        thread.start()

    for thread in threads:
        thread.join()