Python如何在进程运行时进行简单的动画加载
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22029562/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Python how to make simple animated loading while process is running
提问by Fluffball The Wizard
This is pretty much what I have right now:
这几乎是我现在所拥有的:
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'
and I want to get it so that the "while" script would function independently, and it continues to the process, while the animation is going on until the end of the process signals the variable "done" to be 'false', stopping the animation and replacing it with "Done!". This method would be essentially running two scripts at once; is there a way to do it?
并且我想得到它,以便“while”脚本可以独立运行,并继续执行该过程,同时动画进行直到过程结束将变量“done”标记为“false”,从而停止动画并将其替换为“完成!”。这种方法本质上是同时运行两个脚本;有没有办法做到这一点?
回答by Andrew Clark
Use a thread:
使用线程:
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
I also made a couple of minor modifications to your animate()function, the only really important one was adding sys.stdout.flush()after the sys.stdout.write()calls.
我还对您的animate()函数进行了一些小的修改,唯一真正重要的修改是sys.stdout.flush()在sys.stdout.write()调用之后添加。
回答by Alfred George
Try this one
试试这个
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!")
回答by Jansen Simanullang
I see this is a threading problem and not just an animated loading problem. Most the answers provided in this QA thread provides only a pseudocode and left the reader on their own.
我看到这是一个线程问题,而不仅仅是一个动画加载问题。此 QA 线程中提供的大多数答案仅提供伪代码,让读者自行决定。
Here is an answer I am trying to give using a working example of threading and animated loading.
这是我尝试使用线程和动画加载的工作示例给出的答案。
The reader may modify in accordance to their needs.
读者可根据自己的需要进行修改。
# import python packages
# 导入python包
import sys, time, threading
# Define your process.
# 定义你的过程。
# 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')
# Define your animated characters function:
# 定义你的动画角色函数:
def animated_loading():
chars = "/—\|"
for char in chars:
sys.stdout.write('\r'+'loading...'+char)
time.sleep(.1)
sys.stdout.flush()
# define name dan target of your thread
# 定义线程的名称和目标
the_process = threading.Thread(name='process', target=the_process_function)
# start the thread
# 启动线程
the_process.start()
# while the process is alive, call the animated_loading()function
# 当进程还活着时,调用animated_loading()函数
while the_process.isAlive():
animated_loading()
The main steps are outlined in the commented out line.
注释掉的行中概述了主要步骤。
回答by Antonio
import sys, time, threading
def your_function_name() :
# do something here
def loadingAnimation(process) :
while process.isAlive() :
chars = "/—\|"
for char in chars:
sys.stdout.write('\r'+'loading '+char)
time.sleep(.1)
sys.stdout.flush()
loading_process = threading.Thread(target=your_function_name)
loading_process.start()
animated_loading(loading_process)
loading_process.join()
回答by mundiakaluson
Its all done with a few lines of code:
这一切都用几行代码完成:
import time
import os
anime = ["|", "/", "-", "\"]
done = False
while done == False:
for i in anime:
print('Please wait while system is Loading...', i)
os.system('clear')
time.sleep(0.1)
Tested and working successfully in the terminal.
在终端中测试并成功运行。
回答by Python Pro
Here is my code:
这是我的代码:
print("Loading:")
#animation = ["10%", "20%", "30%", "40%", "50%", "60%", "70%", "80%", "90%", "100%"]
animation = ["[■□□□□□□□□□]","[■■□□□□□□□□]", "[■■■□□□□□□□]", "[■■■■□□□□□□]", "[■■■■■□□□□□]", "[■■■■■■□□□□]", "[■■■■■■■□□□]", "[■■■■■■■■□□]", "[■■■■■■■■■□]", "[■■■■■■■■■■]"]
for i in range(len(animation)):
time.sleep(0.2)
sys.stdout.write("\r" + animation[i % len(animation)])
sys.stdout.flush()
print("\n")

