python进度条

本文介绍了一个简单的文本进度条实现方案,使用 Python 的多线程功能来更新和显示进度信息。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

# -*- coding: utf-8 -*-
"""
Created on Sun Jan  4 09:24:28 2015

@author: ydzhao
"""

import os  
import sys  
import cmd  
import unicodedata  
from threading import Thread  
from time import sleep  
  
class ProgressBar(Thread):  
    """A simple text progress bar control."""  
  
    def __init__(self):  
        self.running = True  
        self.percent = -1  
        self.msg = ""  
        Thread.__init__(self)  
  
    def run(self):  
        i = 1  
        while self.running and self.percent < 100:  
            display = '\r'  
  
            if self.msg != "":   
                display += self.msg + ' '  
  
            if self.percent >= 0:  
                display += str(self.percent) + '% '  
                display += '-' * (40 * self.percent / 100)  
  
            if i + 1 + len(display) > 80:   
                i = 1  
  
            display += '-' * i  
            display += '>'  
            display += ' ' * (80 - len(display))  
            sys.stderr.write(display)  
  
            i += 1  
            sleep(0.5)  
  
        sys.stderr.write('\r' + ' ' * 79 + '\r')  
        sys.stderr.flush()  
  
    def stop(self):  
        """Stop displaying progress bar. 
 
        Note: there may be latency to stop. You'd better wait for the thread 
        stops. See _stop_progress(t_bar). 
 
        """  
        self.running = False  
  
    def set_percent(self, percent, msg = ""):  
        """Call back method for owner of progress bar."""  
        self.percent = int(percent)  
        self.msg = msg  
      
    def is_alive(self):  
        return self.isAlive()  
  
  
def _start_progress():  
    """Display a progress bar"""  
    t_bar = ProgressBar()  
    t_bar.start()  
    return t_bar   
  
def _stop_progress(t_bar):  
    """Hide the progress bar"""  
    if hasattr(t_bar, "is_alive"):  
        alive = t_bar.is_alive()  
    else:  
        alive = t_bar.isAlive()  
  
    if t_bar and alive:  
        t_bar.stop()  
        t_bar.join()  
  
def _set_progress(t_bar,percent,msg = ""):  
    t_bar.set_percent(percent,msg)  
      
def _print_msg(t_bar, *args):  
    """Hide the progress bar and print message"""  
  
    assert t_bar is None or isinstance(t_bar, ProgressBar)  
  
    if t_bar and t_bar.is_alive():   
        _stop_progress(t_bar)  
  
    print ' '.join(args)  
  
def _unicode_str_width(text):  
    """Calculate the exact width of unicode string."""  
  
    width = 0  
    for char in text:  
        if isinstance(char, unicode):  
            if unicodedata.east_asian_width(char) in ('F', 'W', 'A'):  
                width += 2  
            else:  
                width += 1  
        else:  
            width += 1  
  
    return width  
      
#Test the progress bar      
if __name__ == "__main__":  
    t_bar = _start_progress()  
    count = 0;  
    while count<100:  
        _set_progress(t_bar,count)  
        sleep(0.1)  
        count = count+1  
          
    _stop_progress(t_bar)  
    print "Done!"  
### STM32CubeMX FreeRTOS CAN Queue Read Example #### 配置项目环境 为了实现基于FreeRTOS的CAN消息队列读取,在STM32CubeMX环境中需完成以下设置: - 使用STM32CubeMX创建新工程并选择目标MCU型号。 - 启用CAN外设支持,并通过RTE(Run-Time Environment)配置其参数,如波特率等。 - 添加对FreeRTOS的支持,这会自动引入必要的库文件和初始化代码。 #### 初始化FreeRTOS与CAN模块 确保已正确设置了`FreeRTOSConfig.h`中的各项参数以适应应用需求[^1]。对于CAN通信部分,则要依据具体硬件平台调整相应的初始化函数调用,通常位于`main.c`或其他由开发者指定的位置。 ```c // main.c or other designated file #include "cmsis_os.h" #include "can.h" osThreadId canReceiveTaskHandle; osMessageQueueId canMsgQueue; void SystemClock_Config(void); static void MX_GPIO_Init(void); static void MX_CAN1_Init(void); int main(void){ HAL_Init(); SystemClock_Config(); MX_GPIO_Init(); MX_CAN1_Init(); osKernelInitialize(); // Initialize CMSIS-OS V2 RTX Kernel // Create the message queue capable of holding up to 10 messages. canMsgQueue = osMessageQueueNew(10, sizeof(CAN_RxHeaderTypeDef), NULL); // Start thread as specified. canReceiveTaskHandle = osThreadNew(can_receive_task, NULL, NULL); osKernelStart(); } ``` #### 创建接收任务处理程序 定义一个专门的任务用于监听来自CAN总线的数据包并通过预先建立的消息队列传递给其他组件进一步解析或响应。 ```c #define MSG_QUEUE_TIMEOUT (10) void can_receive_task(void *argument) { uint8_t rxData[8]; CAN_RxHeaderTypeDef RxHeader; while (true) { if(HAL_CAN_GetRxMessage(&hcan1,&RxHeader,rxData)==HAL_OK){ // Put received data into a queue for processing by another task. osMessageQueuePut(canMsgQueue, &RxHeader, 0, MSG_QUEUE_TIMEOUT); /* Process Data Here */ } osDelay(1); // Short delay between checks } } ``` 上述代码片段展示了如何利用FreeRTOS提供的APIs构建一个多线程应用程序框架下的CAN报文接收机制。每当接收到新的数据帧时即刻将其存入共享资源——消息队列之中等待后续操作;与此同时保持较低优先级循环执行以便让渡CPU时间片给更高紧迫性的作业单元[^2]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值