线程、进程与赛车游戏

  • 时间:
  • 来源:互联网

git使用续

"""
ls 显示当前仓库文件
ls -a 显示当前仓库所有文件,包括隐藏文件

pwd 打印当前工作目录
git clone 仓库地址
git push origin  master
git branch 查看分支
git branch 分支名 建一个新的分支
git checkout 分支名 切换到分支
git merge 分支名 将当前分支和想要合并的分支进行合并
git branch -d 分支名  删除分支
廖雪峰的官网上git教程

"""

正则表达式

import re


def main():
    pattern = re.compile(r'1[345789]\d{9}')
    sentence = '我的手机号是135123456789不是13300998765'
    m = pattern.search(sentence)
    while m :#只要m不为空就继续搜
        print(m.group())
        m = pattern.search(sentence, m.span()[1]) #取出所有匹配,从结束索引开始搜
    
    
if __name__ == '__main__':
    main()
13512345678
13300998765
import re


def main():
    pattern = re.compile(r'1[345789]\d{9}')
    sentence = '我的手机号是135123456789不是13300998765'
    mylist = pattern.findall(sentence) #搜索到所有匹配,并返回一个列表
    #mylist = re.findall(pattern, sentence) 效果同上
    print(mylist)
    #iter - iterator - 迭代器  浪费时间省空间
    for temp in pattern.finditer(sentence):#迭代器,用一个取一个
        print(temp)#打印出的是匹配器对象
        print(temp.group())
        print(temp.span())
if __name__ == '__main__':
    main()
['13512345678', '13300998765']
<_sre.SRE_Match object; span=(6, 17), match='13512345678'>
13512345678
(6, 17)
<_sre.SRE_Match object; span=(20, 31), match='13300998765'>
13300998765
(20, 31)
import re


def main():
    #substitute 替换 匹配到的内容
    sentence = '架飞机卡里面公开囊都Rr'
    r = re.sub('[架开]|飞机|r', '*', sentence, flags=re.IGNORECASE) #第一个参数是需要替换的内容,
    #最后一个参数意思是忽略大小写
    print(r)
    #拆分字符串
    sentence = 'You go your way, I will go mine!'
    mylist = re.split(r'[ ,!]', sentence)
    print(mylist)
if __name__ == '__main__':
    main()
**卡里面公*囊都**
['You', 'go', 'your', 'way', '', 'I', 'will', 'go', 'mine', '']
import re


def main():
    pattern = re.compile(r'(?<=\D)1[345789]\d{9}(?=\D)')#搜索目标前后都不能为数字的
    sentence = '重要的事说1300000000000遍我的手机号是13512345678不是13300998765好'
    
    mylist = pattern.findall(sentence)
    print(mylist)
    
    
    
if __name__ == '__main__':
    main()
['13512345678', '13300998765']
import re


def main():
    sentence = 'aabacddaab'
    # m = re.match(r'a.*b', sentence)#只写*贪婪匹配 取最长的
    m = re.match(r'a.*?b', sentence)#*?惰性匹配 取最短的
    print(m)
    
    
    
if __name__ == '__main__':
    main()
<_sre.SRE_Match object; span=(0, 3), match='aab'>
"""
文字里有数字

"""
import re
pattern = re.compile(r'\d+')
sen = 'abc123dsajfkasdjf46sadfijkak67askdjkl'
mylist = pattern.findall(sen)
print(mylist)

sum = 0
for temp in mylist:
    sum += int(temp)
print(sum/len(mylist))
    
['123', '46', '67']
78.66666666666667
from re import findall, sub


def foo(mo):#mo匹配对象
    val = int(mo.group())
    return str(val ** 2)


def main():
    content = 'abc123dsajfkasdjf46sadfijkak67askdjkl'
    mylist = list(map(int, findall(r'\d+', content))) #高阶函数,对mylist的函数都转换成整数
    print(mylist)
    print(sum(mylist)/len(mylist))
    print(sub(r'\d+', foo, content))#第二个参数可以放函数


if __name__ == '__main__':
    main()
    
[123, 46, 67]
abc15129dsajfkasdjf2116sadfijkak4489askdjkl

进程

  • 操作系统以进程来隔离内存,进程之间是相互隔离的,进程之间通信是IPC协议(如管道,套接字)
"""
使用多进程,多线程的原因
1.为了得到cpu更多的调度,遇到耗时间的任务,可以把任务分解成更多子任务去执行,提高执行效率
,提升性能
2.改善用户体验
"""
import time
from multiprocessing import Process
import os
#导入进程模块
#process 进程
#thread 线程


def output():
    print(os.getpid())
    while True:
        print('ding', end='',flush=True)#flush 是否有缓存True表示不需要缓存
        time.sleep(1)


def main():
    # Process(target=output()).start() 都是定义进程的方法
    print(os.getpid())#打进程号的方法
    p = Process(target=output) #定义的一个进程,一定是赋值的函数名
    p.start()
    while True:
        print('dong', end='',flush=True)
        time.sleep(1)


if __name__ == '__main__':
    main()
import subprocess #子进程


def main():
    subprocess.call('calc') #启动计算器进程


if __name__ == '__main__':
    main()

线程

  • 一个进程可以划分为多个线程,线程是进程的执行单元,也是操作系统分配cpu时间的基本单元,也就是线程越多获得cpu的时间就越多
from time import sleep
from threading import Thread  #导入线程模块

def output():
    while True:
        print('dong', end='', flush=True)
        sleep(0.1)


def main():
    #Thread(target=output).start()
    t1 = Thread(target=output)
    t1.start()
    while True:
        print('ding', end='', flush=True)
        sleep(0.1)

from time import sleep
from threading import Thread  #导入线程模块

def output(string):
    while True:
        print(string, end='', flush=True)
        #sleep(0.001)


def main():
    #Thread(target=output).start()
    t1 = Thread(target=output, args=('dong',),daemon=True)
    # args里是要传参数,而且一定要传元组,deamon表是否是守护线程,会随着主程序的结束而结束
    # 守护线程 - 不值得保存的线程 - 其他线程如果都执行完毕那么守护线程自动结束
    #daemon= True -将线程设置为守护线程
    t1.start()
    t2 = Thread(target=output, args=('ding',), daemon=True)
    t2.start()


if __name__ == '__main__':
    main()
  • 通过下面的代码可以看到线程和进程的区别,线程共用一个变量,而进程是单独使用变量
from time import sleep
from threading import Thread  #导入线程模块
#全局解释器锁,使多线程只能在一个cpu下运行
count = 0
def output(string):
    global count
    while count < 10: #让多个线程总共打印10次
        print(string, end='', flush=True)
        count +=1
        #sleep(0.001)


def main():
    #Thread(target=output).start()
    t1 = Thread(target=output, args=('dong',))
    # args里是要传参数,而且一定要传元组,deamon表是否是守护线程,会随着主程序的结束而结束
    # 守护线程 - 不值得保存的线程 - 其他线程如果都执行完毕那么守护线程自动结束
    #daemon= True -将线程设置为守护线程
    t1.start()
    t2 = Thread(target=output, args=('ding',))
    t2.start()


if __name__ == '__main__':
    main()
from multiprocessing import Process
count = 0
def output(string):
    global count
    while count < 10: #两个进程分别打了十次,内存是相关隔离的
        print(string, end='', flush=True)
        count +=1

def main():

    t1 = Process(target=output, args=('dong',))
    t1.start()
    t2 = Process(target=output, args=('ding',))
    t2.start()

if __name__ == '__main__':
    main()
from time import sleep
from threading import Thread  #导入线程模块
count = 0
def output(string):
    global count
    in_count = 0
    while count < 100: #因为有可能两个同时执行到最后一次所以可能打印出101次
        print(string, end='', flush=True)
        count +=1
        in_count += 1
    print('\n%s打印了%d次' % (string, in_count))

def main():
    #Thread(target=output).start()
    t1 = Thread(target=output, args=('dong',))
    t1.start()
    t2 = Thread(target=output, args=('ding',))
    t2.start()


if __name__ == '__main__':
    main()
from threading import Thread
#创建线程的两种方法
# 1.直接创建Tread对象并通过target参数指定线程启动后要执行的任务
# 2.继承Thread自定义线程,通过重写run方法指定线程启动后执行的任务
class PrintThread(Thread): #定义一个类,继承线程类,通过重写run实现新的功能

    def __init__(self, string, count):
        super().__init__()
        self._string = string
        self._count = count

    def run(self):
        for _ in range(self._count):
            print(self._string, end='', flush=True)

def main():
    PrintThread('ding', 1000).start()
    PrintThread('dong', 1000).start()


if __name__ == '__main__':
    main()
  • 小技巧
    • python 多线程库 from concurrent import futures
      executor.submit 和 futures.as_completed 这个组合比 executor.map 更 灵活,因为 submit 方法能处理不同的可调用对象和参数,而 executor.map 只能处 理参数不同的同一个可调用对象
"""
1.启五个线程,每个线程往同一个列表容器加一万个东西
2.赛车游戏,五个颜色方块表示五辆车,屏幕左右各一条线,看哪个车先到终点
"""
from threading import Thread


class MyThread(Thread):

    def __init__(self, count, string, mylist):
        super().__init__()
        self._count = count
        self._string = string
        self._mylist = mylist

    def run(self):
        for _ in range(self._count):
            self._mylist.append(self._string)



def main():
    mylist = []
    MyThread(10000, '金', mylist).start()
    MyThread(10000, '木', mylist).start()
    MyThread(10000, '水', mylist).start()
    MyThread(10000, '火', mylist).start()
    MyThread(10000, '土', mylist).start()
    for index,x in enumerate(mylist):
        if index % 100 == 0:
            print()
        print(x, end='')
    print(len(mylist))


if __name__ == '__main__':
    main()

赛车游戏

import pygame
from threading import Thread
from random import randint

ranking = []
is_end = True

class Car(Thread):

    def __init__(self, x, y, name, speed, car_color):
        """

        :param x: 车起点的横坐标
        :param y: 车起点的纵坐标
        :param name: 车的名字
        :param speed: 车的速度
        :param car_color: 车的颜色
        """
        super().__init__()
        self._x = x
        self._y = y
        self._name = name
        self._speed = speed
        self._car_color = car_color

    @property
    def x(self):
        return self._x

    @property
    def name(self):
        return self._name

    @property
    def speed(self):
        return self._speed

    def draw(self, screen):
        """画出车"""
        pygame.draw.rect(screen, self._car_color, (self._x, self._y, 20, 20), 0)

    def run(self):
        """让车跑起来"""
        while True:
            if self._speed == 0:
                break
            self._x += self._speed + randint(3, 5)
            t = pygame.time.Clock()
            t.tick(50)

    def arrive(self, race_course):
        """判断到终点"""
        if self._x >= race_course.destination - 20:
            self._speed = 0


class RaceCourse(object):

    def __init__(self, origin, destination):
        """
        
        :param origin: 起点位置
        :param destination: 终点位置
        """
        self._origin = origin
        self._destination = destination

    @property
    def origin(self):
        return  self._origin

    @property
    def destination(self):
        return self._destination

    def draw(self, screen):
        """画地图"""
        pygame.draw.line(screen, [255, 255, 0],
                         (self._origin, 20),(self._origin, 620), 3)
        pygame.draw.line(screen, [255, 0, 0],
                         (self._destination, 20), (self._destination, 620), 3)
        pygame.draw.line(screen, [255, 255, 0],
                         (self._origin, 20), (self._destination, 20), 3)
        pygame.draw.line(screen, [255, 255, 0],
                         (self._origin, 140), (self._destination, 140), 3)
        pygame.draw.line(screen, [255, 255, 0],
                         (self._origin, 260), (self._destination, 260), 3)
        pygame.draw.line(screen, [255, 255, 0],
                         (self._origin, 380), (self._destination, 380), 3)
        pygame.draw.line(screen, [255, 255, 0],
                         (self._origin, 500), (self._destination, 500), 3)
        pygame.draw.line(screen, [255, 255, 0],
                         (self._origin, 620), (self._destination, 620), 3)




def create(num=5):
    """

    :param num: 赛车的数量
    :return: 在地图上随机产生小车
    """
    cars = []
    cars_name = ['剃刀', '大Q吧', '金刚狼', '卓越', '黑色闪电']
    for n in range(num):
        car = Car(20, 70 + n * 120, cars_name[n], randint(5,10),
                  [randint(0, 255), randint(0, 255), randint(0, 255)] )
        cars.append(car)
    return cars


def main():


    def rank():
        """监视到终点的顺序"""
        global is_end
        while is_end:
            nonlocal cars
            global ranking
            for y in range(5):
                if cars[y].speed == 0 and len(ranking) < 5 and cars[y] not in ranking:
                    ranking.append(cars[y])
                if len(ranking) == 5:
                    is_end = False


    def refresh():
        """刷新界面"""
        x = ''
        global ranking
        if len(cars) == len(ranking):
            for ca in ranking:
                x += ca.name + ','
            score_board = score.render("名次依次是: %s" % x, True, [0, 0, 0])
            text_board = score_board.get_rect()
            text_board.center = (600, 300)
            screen.blit(score_board, text_board)
            pygame.display.update()
        screen.fill([242, 242, 242])
        for car in cars:
            car.draw(screen)
            car.arrive(race)
        race.draw(screen)
        pygame.display.flip()

    pygame.init()
    score = pygame.font.SysFont('SimHei', 32)
    screen = pygame.display.set_mode((1200, 640))
    pygame.display.set_caption('QQ飞车')
    screen.fill([242, 242, 242])
    cars = create(5)
    for car in cars:
        car.draw(screen)
    race = RaceCourse(40,1160)
    race.draw(screen)
    Thread(target=rank, daemon=True).start()
    pygame.display.flip()
    running = True
    while running:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                running = False
            elif event.type == pygame.KEYDOWN:
                if event.key == pygame.K_F2: # F2开始游戏
                    for car in cars:
                        car.start()
                elif event.key == pygame.K_r: #R重置游戏
                    cars = create(5)
                    global ranking
                    ranking = []
                    global is_end
                    is_end = True
                    Thread(target=rank, daemon=True).start()

        refresh()
    pygame.quit()


if __name__ == '__main__':
    main()

本文链接http://element-ui.cn/news/show-576554.aspx