Python异步处理的返回进度怎样用进度条展现
Admin 2022-09-09 群英技术资讯 280 次浏览
Python异步处理,新起一个进程返回处理进度
使用 tqdm 和 multiprocessing.Pool
安装
pip install tqdm
代码
import time import threading from multiprocessing import Pool from tqdm import tqdm def do_work(x): time.sleep(x) return x def progress(): time.sleep(3) # 3秒后查进度 print(f'任务有: {pbar.total} 已完成:{pbar.n}') tasks = range(10) pbar = tqdm(total=len(tasks)) if __name__ == '__main__': thread = threading.Thread(target=progress) thread.start() results = [] with Pool(processes=5) as pool: for result in pool.imap_unordered(do_work, tasks): results.append(result) pbar.update(1) print(results)
效果
安装
pip install flask
main.py
import time from multiprocessing import Pool from tqdm import tqdm from flask import Flask, make_response, jsonify app = Flask(__name__) def do_work(x): time.sleep(x) return x total = 5 # 总任务数 tasks = range(total) pbar = tqdm(total=len(tasks)) @app.route('/run/') def run(): """执行任务""" results = [] with Pool(processes=2) as pool: for _result in pool.imap_unordered(do_work, tasks): results.append(_result) if pbar.n >= total: pbar.n = 0 # 重置 pbar.update(1) response = make_response(jsonify(dict(results=results))) response.headers.add('Access-Control-Allow-Origin', '*') response.headers.add('Access-Control-Allow-Headers', '*') response.headers.add('Access-Control-Allow-Methods', '*') return response @app.route('/progress/') def progress(): """查看进度""" response = make_response(jsonify(dict(n=pbar.n, total=pbar.total))) response.headers.add('Access-Control-Allow-Origin', '*') response.headers.add('Access-Control-Allow-Headers', '*') response.headers.add('Access-Control-Allow-Methods', '*') return response
启动(以 Windows 为例)
set FLASK_APP=main flask run
接口列表
test.html
<!DOCTYPE html> <html lang="zh"> <head> <meta charset="UTF-8"> <title>进度条</title> <script src="https://cdn.bootcss.com/jquery/3.0.0/jquery.min.js"></script> <script src="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/3.3.7/js/bootstrap.min.js"></script> <link href="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css" rel="external nofollow" rel="stylesheet"> </head> <body> <button id="run">执行任务</button> <br><br> <div class="progress"> <div class="progress-bar" role="progressbar" aria-valuenow="1" aria-valuemin="0" aria-valuemax="100" style="width: 10%">0.00% </div> </div> </body> <script> function set_progress_rate(n, total) { //设置进度 var rate = (n / total * 100).toFixed(2); if (n > 0) { $(".progress-bar").attr("aria-valuenow", n); $(".progress-bar").attr("aria-valuemax", total); $(".progress-bar").text(rate + "%"); $(".progress-bar").css("width", rate + "%"); } } $("#run").click(function () { //执行任务 $.ajax({ url: "http://127.0.0.1:5000/run/", type: "GET", success: function (response) { set_progress_rate(100, 100); console.log('执行完成,结果为:' + response['results']); } }); }); setInterval(function () { //每1秒请求一次进度 $.ajax({ url: "http://127.0.0.1:5000/progress/", type: "GET", success: function (response) { console.log(response); var n = response["n"]; var total = response["total"]; set_progress_rate(n, total); } }); }, 1000); </script> </html>
效果
在Flask中使用简单异步任务最简洁优雅的原生实现:
from flask import Flask from time import sleep from concurrent.futures import ThreadPoolExecutor # DOCS https://docs.python.org/3/library/concurrent.futures.html#concurrent.futures.ThreadPoolExecutor executor = ThreadPoolExecutor(2) app = Flask(__name__) @app.route('/jobs') def run_jobs(): executor.submit(some_long_task1) executor.submit(some_long_task2, 'hello', 123) return 'Two jobs was launched in background!' def some_long_task1(): print("Task #1 started!") sleep(10) print("Task #1 is done!") def some_long_task2(arg1, arg2): print("Task #2 started with args: %s %s!" % (arg1, arg2)) sleep(5) print("Task #2 is done!") if __name__ == '__main__': app.run()
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:mmqy2019@163.com进行举报,并提供相关证据,查实之后,将立刻删除涉嫌侵权内容。
猜你喜欢
这篇文章主要介绍了使用numpy.ndarray添加元素,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
通过NETCONF,网管能够用可视化的界面统一管理网络中的设备,并且安全性高、可靠性强、扩展性强。如下图所示,网管与网络中的所有交换机之间建立NETCONF会话,用户即可在网管提供的可视化界面上对网络中的所有交换机进行统一的管理,提高网络运维效率。
Python内置函数-float()函数。float() 函数用于将整数和字符串转换成浮点数。
这篇文章主要为大家介绍了python人工智能tensorflow构建循环神经网络RNN,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪
这篇文章主要介绍了Python如何匹配文本并在其上一行追加文本,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
成为群英会员,开启智能安全云计算之旅
立即注册Copyright © QY Network Company Ltd. All Rights Reserved. 2003-2020 群英 版权所有
增值电信经营许可证 : B1.B2-20140078 粤ICP备09006778号 域名注册商资质 粤 D3.1-20240008