异步进程微调器

2024-06-02 13:34:36 发布

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

这是进度微调器的代码:

import sys
import time

def spinning_cursor():
    while True:
        for cursor in '|/-\\':
            yield cursor

spinner = spinning_cursor()
for _ in range(50):
    sys.stdout.write(spinner.next())
    sys.stdout.flush()
    time.sleep(10)
    sys.stdout.write('\b')

输出

python2.7 test.py
|

它旋转得非常慢,因为循环休眠了10秒

在进程处于休眠状态时,如何继续旋转旋转器


Tags: 代码inimporttruefortimedefstdout
3条回答

产生两个线程,AB。线程A运行cmd完成。线程B显示旋转光标并等待线程A退出,这将在cmd完成时发生。此时,线程B清除旋转光标,然后退出

或者使用现有的库,而不是重新发明轮子。考虑progressbar库。您将需要RotatingMarker进度指示器

你可以小步入睡,直到达到10秒:

import sys, time

def spinning_cursor():
    while True:
        for cursor in '|/-\\':
            yield cursor

spinner = spinning_cursor()
end_time = time.time() + 10
while time.time() < end_time:
    sys.stdout.write(spinner.next())
    sys.stdout.flush()
    time.sleep(0.2) # adjust this to change the speed
    sys.stdout.write('\b')

但这会阻塞主线程,因此只有当您想等待10秒而不在Python程序中执行任何其他操作(例如,等待某个外部进程完成)时,它才有用

如果希望在微调器旋转时运行其他Python代码,则需要两个线程,一个用于微调器,一个用于主要工作。您可以这样设置:

import sys, time, threading

def spin_cursor():
    while True:
        for cursor in '|/-\\':
            sys.stdout.write(cursor)
            sys.stdout.flush()
            time.sleep(0.1) # adjust this to change the speed
            sys.stdout.write('\b')
            if done:
                return

# start the spinner in a separate thread
done = False
spin_thread = threading.Thread(target=spin_cursor)
spin_thread.start()

# do some more work in the main thread, or just sleep:
time.sleep(10)

# tell the spinner to stop, and wait for it to do so;
# this will clear the last cursor before the program moves on
done = True
spin_thread.join()

# continue with other tasks
sys.stdout.write("all done\n")

您必须创建一个单独的线程。下面的示例大致说明了如何做到这一点。然而,这只是一个简单的例子

import sys
import time

import threading


class SpinnerThread(threading.Thread):

    def __init__(self):
        super().__init__(target=self._spin)
        self._stopevent = threading.Event()

    def stop(self):
        self._stopevent.set()

    def _spin(self):

        while not self._stopevent.isSet():
            for t in '|/-\\':
                sys.stdout.write(t)
                sys.stdout.flush()
                time.sleep(0.1)
                sys.stdout.write('\b')


def long_task():
    for i in range(10):
        time.sleep(1)
        print('Tick {:d}'.format(i))


def main():

    task = threading.Thread(target=long_task)
    task.start()

    spinner_thread = SpinnerThread()
    spinner_thread.start()

    task.join()
    spinner_thread.stop()


if __name__ == '__main__':
    main()

相关问题 更多 >