一、Linux的shell的程序运行命令行进度条的实现 1.简单的单行进度条 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 #!/bin/bash num=0 str='' max=100 postfix=('|' '/' '-' '\' ) while [ $num -le $max ]do let index=num%4 printf "[%-50s %-2d%% %c]\r" "$str " "$num " "${postfix[$index]} " let num++ sleep 0.1 if (($num % 2 == 0 )); then str+='#' fi done printf "\n"
在windows中运行该文件,新建文本文件,输入文本后保存为001.sh,需要下载git并安装好,打开git bash,输入命令
2带输出内容的单行进度条 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 #!/bin/bash num=0 str='' max=100 postfix=('|' '/' '-' '\' ) while [ $num -le $max ]do let index=num%4 shellwidth=`stty size | awk '{print $2}' ` shellwidthstr="%-" $shellwidth "s\n" fmt_str="now " $num " shell tty width " $shellwidth printf "$shellwidthstr " "$fmt_str " printf "[%-50s %-2d%% %c]\r" "$str " "$num " "${postfix[$index]} " let num++ sleep 0.1 if (($num % 2 == 0 )); then str+='#' fi done printf "\n"
二、matlab实现命令行窗口的进度条 一般matlab的进度条都是用waitbar函数来实现,但是这个命令会创建一个新的进度条窗口,虽然很美观,但是有时候还是会出现一些问题。例如,一般进度条程序都是嵌入在程序里面,当你不小心删除了进度条窗口后,程序就会报错退出,这样我们花大把时间算的就功亏一篑了,实在难受。所以就想到了,做一个类似Linux的命令行加载的进度条,在matlab的命令行窗口输出。这样就不会出现上述问题了。
1.单行进度条的实现 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 function SingleLineProgressBar num=0 ; str='' ; MyDataLength=100 ; BarMaxLength=70 ; postfix=['|' '/' '-' '\' ]; for i =1 :MyDataLength fprintf(repmat ('\b' ,1 ,num)); num=fprintf('[%s %.2f%% %c ]' ,str,(i /MyDataLength)*100 ,postfix(mod (i ,4 )+1 )); if (i /MyDataLength)>(strlength(str)/BarMaxLength) str=str+"#" ; end pause(0.1 ); end fprintf("\n" ); end
仿照了Linux写的一个脚本程序,看效果:
总体感觉还行,但是由于不知道如何获取当前命令行窗口的长度和当前文本格式下字符串的长度,所以无法做到自适应,只能认为测量一下大概的长度,然后提前设定BarMaxLength的值。
2.带输出内容的单行进度条实现 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 function SingleLineProgressBar disp ("程序开始执行" )disp ("数据计算中........." )pause(1 ); num=0 ; str='' ; MyDataLength=100 ; BarMaxLength=70 ; postfix=['|' '/' '-' '\' ]; for i =1 :MyDataLength fprintf(repmat ('\b' ,1 ,num)); fprintf("当前数据执行第%d个,总体共%d个\n" ,i ,MyDataLength); num=fprintf('[%s %.2f%% %c ]' ,str,(i /MyDataLength)*100 ,postfix(mod (i ,4 )+1 )); if (i /MyDataLength)>(strlength(str)/BarMaxLength) str=str+"#" ; end pause(0.1 ); end fprintf("\n" ); end
这个只是加了一点点,在进度条输出前输出你想输出的内容就行了,还是比较简单的,看一下效果: