zoukankan      html  css  js  c++  java
  • 老王Python-进阶篇4-多线程1.1

    习题一:已知列表 info = [1,2,3,4,55,233],生成6个线程对象,每次线程输出一个值,最后输出:"the end"。

     1 import threading
     2 
     3 def test(j):
     4     print j
     5 
     6 ts=[]
     7 info = [1,2,3,4,55,233]
     8 for j in info:
     9     th=threading.Thread(target=test,args=[j])
    10     th.start()
    11     ts.append(th)
    12 
    13 for i in ts:
    14     i.join()
    15 
    16 print 'end'

    习题二:已知列表 urlinfo = ['http://www.sohu.com','http://www.163.com','http://www.sina.com'] 用多线程的方式分别打开列表里的URL,并且输出对应的网页标题和内容。

    import urllib,re,threading
    
    def func(url_new):
        try:
            f=urllib.urlopen(url_new)
        except IOError:
            print 'error'
        else:
            content= f.read()
            a=re.compile('<title>.*</title>')  #
            foundLabel = a.search(content)
            finalLabel=foundLabel.group()
            print content,finalLabel
    
    if __name__=='__main__':
        url_list=['http://www.163.com','http://www.sina.com','http://www.sohu.com']
    
        ts=[]
        for j in url_list:
            th=threading.Thread(target=func,args=[j])
            th.start()
            ts.append(th)
    
        for i in ts:
            i.join()
    
        print 'end'

    习题三:已知列表 urlinfo = ['http://www.sohu.com','http://www.163.com','http://www.sina.com'] 用多线程的方式分别打开列表里的URL,输出网页的http状态码

    import urllib,re,threading
    
    def func(url_new):
        try:
            f=urllib.urlopen(url_new)
        except IOError:
            print 'error'
        else:
            code=f.code
            content= f.read()
            a=re.compile('<title>.*</title>')  #正则表达式查找标题
            foundLabel = a.search(content)
            finalLabel=foundLabel.group()
            print [code],finalLabel
    
    if __name__=='__main__':
        url_list=['http://www.163.com','http://www.sina.com','http://www.sohu.com']
    
        ts=[]
        for j in url_list:
            th=threading.Thread(target=func,args=[j])
            th.start()
            ts.append(th)
    
        for i in ts:
            i.join()
    
        print 'end'
  • 相关阅读:
    JavaScript Validator 报错
    JSP项目_Web路径_磁盘物理路径
    TreaponseHeader
    TrequestHeader
    HTML学习笔记1
    SQL文摘:DATE_TRUNC: A SQL Timestamp Function You Can Count On
    SQL文摘:Writing Subqueries in SQL
    Python文摘:Requests (Adavanced Usage)
    Python文摘:Requests
    Python文摘:More About Unicode in Python 2 and 3
  • 原文地址:https://www.cnblogs.com/duyaya/p/8306591.html
Copyright © 2011-2022 走看看