Python如何在进程运行时进行简单的动画加载

2024-05-07 04:24:30 发布

您现在位置:Python中文网/ 问答频道 /正文

这就是我现在所拥有的:

import time
import sys

done = 'false'
#here is the animation
def animate():
    while done == 'false':
        sys.stdout.write('\rloading |')
        time.sleep(0.1)
        sys.stdout.write('\rloading /')
        time.sleep(0.1)
        sys.stdout.write('\rloading -')
        time.sleep(0.1)
        sys.stdout.write('\rloading \\')
        time.sleep(0.1)
    sys.stdout.write('\rDone!     ')

animate()
#long process here
done = 'false'

我想得到它,这样“while”脚本将独立运行,并且它将继续运行到进程中,而动画将继续运行,直到进程结束时将变量“done”标记为“false”,停止动画并将其替换为“done!”。这个方法实际上是一次运行两个脚本;有没有办法做到这一点?


Tags: import脚本falseheretime进程stdoutsys
3条回答

使用线程:

import itertools
import threading
import time
import sys

done = False
#here is the animation
def animate():
    for c in itertools.cycle(['|', '/', '-', '\\']):
        if done:
            break
        sys.stdout.write('\rloading ' + c)
        sys.stdout.flush()
        time.sleep(0.1)
    sys.stdout.write('\rDone!     ')

t = threading.Thread(target=animate)
t.start()

#long process here
time.sleep(10)
done = True

我还对animate()函数做了一些小修改,唯一真正重要的修改是在sys.stdout.write()调用之后添加sys.stdout.flush()

试试这个

import time
import sys


animation = "|/-\\"

for i in range(100):
    time.sleep(0.1)
    sys.stdout.write("\r" + animation[i % len(animation)])
    sys.stdout.flush()
    #do something
print("End!")

我看到这是一个线程问题,而不仅仅是一个动画加载问题。这个QA线程中提供的大多数答案都只提供了一个伪代码,让读者自己处理。

下面是我试图用线程和动画加载的工作示例给出的答案。

读取器可以根据其需要进行修改。

#导入python包

import sys, time, threading

#定义流程

 # Here is an example of the process function:

def the_process_function():
    n = 20
    for i in range(n):
        time.sleep(1)
        sys.stdout.write('\r'+'loading...  process '+str(i)+'/'+str(n)+' '+ '{:.2f}'.format(i/n*100)+'%')
        sys.stdout.flush()
    sys.stdout.write('\r'+'loading... finished               \n')

#定义动画角色功能:

def animated_loading():
    chars = "/—\|" 
    for char in chars:
        sys.stdout.write('\r'+'loading...'+char)
        time.sleep(.1)
        sys.stdout.flush() 

#定义线程的名称和目标

the_process = threading.Thread(name='process', target=the_process_function)

#启动线程

the_process.start()

#当进程处于活动状态时,调用animated_loading()函数

while the_process.isAlive():
    animated_loading()

注释行中概述了主要步骤。

相关问题 更多 >