我正在编写一个小API,使我的python命令行输出看起来更好一点。但是仍然有一个大问题,因为我希望能够调用像display_loading_until_event(text)
这样的函数,它应该:
- 立即返回"完成"的方法;加载动画
- 每0.25秒更新一次加载动画
我也尝试使用multiprocessing
库中的Process
,但它似乎不起作用:
from time import sleep
def display_loading_until_event(message):
from multiprocessing import Process
class Stop:
def __init__(self):
self.run = True
class LoadingAnimationProcess(Process):
def __init__(self, stopper, *args, **kwargs):
Process.__init__(self, *args, **kwargs)
self.stop = stopper
def run(self):
def get_loading(position):
return positions[position] # Returns the way the loading animation looks like (position: ["", "|", "-"])
print(get_loading(0), end=message) # Simplified version
pos = 0
while self.stop.run:
sleep(0.25)
pos = pos + 1
print("r" + get_loading(pos) + message, end="") # Again, simplified
if pos == len(positions) - 1:
pos = -1
sleep(0.25)
print("r" + "✔" + message) # Prints ✔ to signal that the loading is done
stopper = Stop()
loading = LoadingAnimationProcess(stopper)
loading.start() # Starts the process
def stop():
stopper.run = False
sleep(1)
# loading.join() ???
return stop # This therefore returns a function to stop the loading, right?
# So this should in theory work:
positions = ["\", "|", "-"]
endfnc = display_loading_until_event("Hello loading")
sleep(4)
endfnc()
# And now the loading SHOULD STOP
这段代码只是一个例子,实际的代码要复杂一点,但应该这样做。加载动画在powershell上不起作用(r
是破坏它的东西)
当前代码工作,display_loading_until_event
调用后的所有内容都被执行,但加载不会停止。
我也不认为这样做是正确的…
就是这样:如何结束一个while循环在另一个线程?
我只是返回"condition。set"方法和它的工作!