以文件复制器的代码为例
import os
import multiprocessing
def copy_file(q
, i
, file_names
, new_file
, file_list
):
"""复制文件处理"""
open_file
= open(file_names
+"/"+i
, "rb")
content
= open_file
.read
()
open_file
.close
()
new_open_file
= open(new_file
+"/"+i
, "wb")
new_open_file
.write
(content
)
new_open_file
.close
()
q
.put
(i
)
def main():
current_file
= os
.listdir
(os
.getcwd
())
file_names
= input("请输入要复制的文件夹:")
if file_names
in current_file
:
try:
new_file
= file_names
+ "[复件]"
os
.mkdir
(new_file
)
except:
pass
file_list
= os
.listdir
(file_names
)
q
= multiprocessing
.Manager
().Queue
()
old_file_num
= len(file_list
)
po
= multiprocessing
.Pool
(5)
for i
in file_list
:
po
.apply_async
(copy_file
, args
=(q
, i
, file_names
, new_file
, file_list
))
po
.close
()
copy_ok
= 0
while True:
file_name
= q
.get
()
copy_ok
+= 1
print("\r完成%.2f %%" % (copy_ok
*100 / old_file_num
), end
="")
if copy_ok
>= old_file_num
:
break
else:
print("当前目录下没有该文件")
if __name__
== "__main__":
main
()
print()
实验结果: 最后的百分比会从1%升到100%
·
进度百分比的实现事实上是在无限循环中通过输出重复覆盖实现的,如上代码中
print("\r完成%.2f %%" % (copy_ok
*100 / old_file_num
), end
="")
这里前面的 ‘\r’转义字符是将光标移到一行的开始,所以\r之后的内容会覆盖掉上次打印的内容 这里通过重复的覆盖上一条输出,从而展现进度百分比从1%到100%的动态显示