Python 官方文档:入门教程 => 点击学习
利用python多进程+进度条实现一个有意思的小程序import random import time import sys from multiprocessing import 
利用python多进程+进度条实现一个有意思的小程序
import random
import time
import sys
from multiprocessing import Process
def processBar_tortoise(num, total, name_icon): # 进度条
rate = num / total
rate_num = int(rate * 100)
s = '起点 ' + '> ' * (total-2) + '终点'
if rate_num == 100:
s = s.split()
s[num] = name_icon
y = ''.join(s)
r = '\r{}\n'.fORMat(y)
else:
s = s.split()
s[num] = name_icon
y = ''.join(s)
r = '\r{}'.format(y)
sys.stdout.write(r)
sys.stdout.flush
def processBar_hare(num, total, name_icon): # 进度条
rate = num / (total+1)
rate_num = int(rate * 100)
s = '起点 ' + '> ' * (total-3) + '终点'
if rate_num == 100:
s = s.split()
s[num] = name_icon
y = ''.join(s)
r = '\r{}\n'.format(y)
else:
s = s.split()
s[num] = name_icon
y = ''.join(s)
r = '\r{}'.format(y)
sys.stdout.write(r)
sys.stdout.flush
def tortoise(total_step):
start_time = time.time()
step = 0
while step < total_step:
time.sleep(0.2)
step += 1
processBar_tortoise(step, total_step+1, '?')
end_time = time.time()
print('\n乌龟花了多少时间:{:.2f}'.format(end_time-start_time))
def hare(total_step):
start_time = time.time()
step = 0
flags = [1, 0]
while step < total_step:
time.sleep(0.2)
sleeping = flags[int(random.random() * 10) % 2]
if sleeping:
processBar_hare(step, total_step, '?zzz')
else:
step += 2
processBar_hare(step, total_step+2, '?')
end_time = time.time()
print('\n兔子花了多少时间:{:.2f}'.format(end_time - start_time))
if __name__ == '__main__':
t = Process(target=tortoise, args=(20,))
h = Process(target=hare, args=(20,))
t.start()
h.start()
效果图:
--结束END--
本文标题: python进程+进度条实现赛跑效果
本文链接: https://www.lsjlt.com/news/179153.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
下载Word文档到电脑,方便收藏和打印~
2024-03-01
2024-03-01
2024-03-01
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0