31. Python多线程的使用
流程:定义程序,建立新线程,主线程进入死循环(不然程序就结束了),子线程循环执行
import _thread
import time
def print_time(threadName,delay):
count = 0
while count < 5:
time.sleep(delay)
count += 1
print("%s:%s" % (threadName,time.ctime(time.time())))
#建立两个新的线程
try:
_thread.start_new_thread(print_time,("thread-1",2)) #传入函数名称,传入函数参数
_thread.start_new_thread(print_time, ("thread-2",3))
except:
print("Can't create thread")
while 1:
pass
32.Python错误处理,构建一个不存在的prints函数,因为是脚本语言因此前期不会检查到错误,只有解释时候才会检测到错误并且返回错误值
import _thread
import time
def prints(str):
print(str+"s")
try:
print("hello")
prints("mod")
except Exception as er:
print(er)
33. Python读取文件,流程是使用open函数打开txt文本文件,写入文件然后关闭文件,再以读取方式打开文件
import _thread
import time
def prints(str):
print(str+"s")
try:
fh1 = open("e:/c6.txt","w")
fh1.writelines("line1")
fh1.close()
fh2 = open("e:/c6.txt","r")
print(fh2.readline())
except Exception as er:
print("Open file failure")
print(er)
34.Python使用正则表达式检索字符串
简单的搜索baidu在网址字符串中的位置
import re
pat="baidu"
string = "http://www.baidu.com"
rst1 = re.search(pat,string)
print(rst1)
执行结果:<_sre.SRE_Match object; span=(11, 16), match='baidu'>
35.Python使用正则表达式提取网页
加载一个课程预定的页面,利用正则表达式提取出网页指定标签(strong标签内)的内容
import re
import urllib.request
pat="<strong>[\\x0a-\\xf0](.*?)</strong>"
data =urllib.request.urlopen( "https://edu.csdn.net/huiyiCourse/detail/819").read()
rst1 = re.compile(pat).findall(str(data))
print(rst1)