如何创建旋转命令行游标?


Answers:


80

假设您的终端处理\ b,则类似这样

import sys
import time

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

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

13
您可能需要使用spinner = itertools.cycle(['-', '/', '|', '\\'])而不是创建一个生成器功能(更简洁,更重用)如图所示这里
达明

7
请注意,在Python 3中,spinner.next()替换为next(spinner);参见stackoverflow.com/a/1073582/5025060
CODE-READ 2016年

49

易于使用的API(将在单独的线程中运行微调器):

import sys
import time
import threading

class Spinner:
    busy = False
    delay = 0.1

    @staticmethod
    def spinning_cursor():
        while 1: 
            for cursor in '|/-\\': yield cursor

    def __init__(self, delay=None):
        self.spinner_generator = self.spinning_cursor()
        if delay and float(delay): self.delay = delay

    def spinner_task(self):
        while self.busy:
            sys.stdout.write(next(self.spinner_generator))
            sys.stdout.flush()
            time.sleep(self.delay)
            sys.stdout.write('\b')
            sys.stdout.flush()

    def __enter__(self):
        self.busy = True
        threading.Thread(target=self.spinner_task).start()

    def __exit__(self, exception, value, tb):
        self.busy = False
        time.sleep(self.delay)
        if exception is not None:
            return False

现在with在代码中任意位置的块中使用它:

with Spinner():
  # ... some long-running operations
  # time.sleep(3) 

6
直到您在未处理的代码中遇到错误之前,这真的很不错。然后,您不能强迫它停止。
DDuffy

float(delay)将提高如果没有浮动,应该是isinstance(delay, Number),与Numbernumbers
levsa

嘿,院长,我对此很业余,但这看起来真的很好。您能举一个“ with Spinner()”的例子吗?显然,我还不太了解。@Victor Moyseenko
Mike_Leigh

41

一个很好的pythonic方法是使用itertools.cycle:

import itertools, sys
spinner = itertools.cycle(['-', '/', '|', '\\'])
while True:
    sys.stdout.write(next(spinner))   # write the next character
    sys.stdout.flush()                # flush stdout buffer (actual character display)
    sys.stdout.write('\b')            # erase the last written char

另外,您可能希望在长函数调用期间使用线程来显示微调框,例如http://www.interclasse.com/scripts/spin.php


4
根据CODE-REaD在另一个答案中的注释,在python 3中,使用next(spinner)代替spinner.next()
Siyh

2
简单使用更简洁spinner = itertools.cycle('-/|\\')
martineau

1
@martineau更简洁,但可以理解的却更少。
Noctis Skytower

1
@NoctisSkytower:可以说。
martineau

它永远运行,我尝试使用线程,它仍然疯狂运行,老兄。如果它是一个thread3,我如何使其在t1开始时运行,并在t2完成时停止运行?有什么提示吗?
Mike_Leigh20年

11

一个办法:

import sys
import time

print "processing...\\",
syms = ['\\', '|', '/', '-']
bs = '\b'

for _ in range(10):
    for sym in syms:
        sys.stdout.write("\b%s" % sym)
        sys.stdout.flush()
        time.sleep(.5)

关键是使用退格字符'\ b'和flush stdout。


6

@Victor Moyseenko的改进版本,因为原始版本几乎没有问题

  1. 旋转完成后离开旋转器的角色
  2. 有时也导致删除以下输出的第一个字符
  3. 通过将threading.Lock()放在输出上避免了罕见的竞争情况
  4. 当没有tty可用(不旋转)时,返回到更简单的输出
import sys
import threading
import itertools
import time

class Spinner:

    def __init__(self, message, delay=0.1):
        self.spinner = itertools.cycle(['-', '/', '|', '\\'])
        self.delay = delay
        self.busy = False
        self.spinner_visible = False
        sys.stdout.write(message)

    def write_next(self):
        with self._screen_lock:
            if not self.spinner_visible:
                sys.stdout.write(next(self.spinner))
                self.spinner_visible = True
                sys.stdout.flush()

    def remove_spinner(self, cleanup=False):
        with self._screen_lock:
            if self.spinner_visible:
                sys.stdout.write('\b')
                self.spinner_visible = False
                if cleanup:
                    sys.stdout.write(' ')       # overwrite spinner with blank
                    sys.stdout.write('\r')      # move to next line
                sys.stdout.flush()

    def spinner_task(self):
        while self.busy:
            self.write_next()
            time.sleep(self.delay)
            self.remove_spinner()

    def __enter__(self):
        if sys.stdout.isatty():
            self._screen_lock = threading.Lock()
            self.busy = True
            self.thread = threading.Thread(target=self.spinner_task)
            self.thread.start()

    def __exit__(self, exception, value, tb):
        if sys.stdout.isatty():
            self.busy = False
            self.remove_spinner(cleanup=True)
        else:
            sys.stdout.write('\r')

上面的Spinner类的使用示例:


with Spinner("just waiting a bit.. "):

        time.sleep(3)

将代码上传到https://github.com/Tagar/stuff/blob/master/spinner.py


4

漂亮,简单,干净...

while True:
    for i in '|\\-/':
        print('\b' + i, end='')

4

例

为了完整性,我想添加一个很棒的包halo。它提供了许多预设微调器和更高级别的自定义选项。

从他们的自述中摘录

from halo import Halo

spinner = Halo(text='Loading', spinner='dots')
spinner.start()

# Run time consuming work here
# You can also change properties for spinner as and when you want

spinner.stop()

或者,您可以将halo与Python的with语句一起使用:

from halo import Halo

with Halo(text='Loading', spinner='dots'):
    # Run time consuming work here

最后,您可以使用halo作为装饰器:

from halo import Halo

@Halo(text='Loading', spinner='dots')
def long_running_function():
    # Run time consuming work here
    pass

long_running_function()





1

我在GitHub上找到了py-spin包。它具有许多不错的旋转样式。以下是关于如何使用一些样本,Spin1\-/风格:

from __future__ import print_function

import time

from pyspin.spin import make_spin, Spin1

# Choose a spin style and the words when showing the spin.
@make_spin(Spin1, "Downloading...")
def download_video():
    time.sleep(10)

if __name__ == '__main__':
    print("I'm going to download a video, and it'll cost much time.")
    download_video()
    print("Done!")
    time.sleep(0.1)

也可以手动控制旋转:

from __future__ import print_function

import sys
import time

from pyspin.spin import Spin1, Spinner

# Choose a spin style.
spin = Spinner(Spin1)
# Spin it now.
for i in range(50):
    print(u"\r{0}".format(spin.next()), end="")
    sys.stdout.flush()
    time.sleep(0.1)

以下gif中的其他样式。

py-spin软件包中的旋转样式。


0
#!/usr/bin/env python

import sys

chars = '|/-\\'

for i in xrange(1,1000):
    for c in chars:
        sys.stdout.write(c)
        sys.stdout.write('\b')
        sys.stdout.flush()

请注意: 根据我的经验,这并不适用于所有终端。在Unix / Linux下,更健壮的方法是使用curses模块,因为它更为复杂,而该模块在Windows下不起作用。您可能希望通过后台正在进行的实际处理来减慢其速度。


0

在这里-简单明了。

import sys
import time

idx = 0
cursor = ['|','/','-','\\'] #frames of an animated cursor

while True:
    sys.stdout.write(cursor[idx])
    sys.stdout.write('\b')
    idx = idx + 1

    if idx > 3:
        idx = 0

    time.sleep(.1)

0

粗略但简单的解决方案:

import sys
import time
cursor = ['|','/','-','\\']
for count in range(0,1000):
  sys.stdout.write('\b{}'.format(cursor[count%4]))
  sys.stdout.flush()
  # replace time.sleep() with some logic
  time.sleep(.1)

有明显的局限性,但又很粗糙。


0

我提出使用装饰器的解决方案

from itertools import cycle
import functools
import threading
import time


def spinner(message, spinner_symbols: list = None):
    spinner_symbols = spinner_symbols or list("|/-\\")
    spinner_symbols = cycle(spinner_symbols)
    global spinner_event
    spinner_event = True

    def start():
        global spinner_event
        while spinner_event:
            symbol = next(spinner_symbols)
            print("\r{message} {symbol}".format(message=message, symbol=symbol), end="")
            time.sleep(0.3)

    def stop():
        global spinner_event
        spinner_event = False
        print("\r", end="")

    def external(fct):
        @functools.wraps(fct)
        def wrapper(*args):
            spinner_thread = threading.Thread(target=start, daemon=True)
            spinner_thread.start()
            result = fct(*args)
            stop()
            spinner_thread.join()

            return result

        return wrapper

    return external

使用简单

@spinner("Downloading")
def f():
    time.sleep(10)

0

我建立了一个通用的Singleton,由整个应用程序共享

from itertools import cycle
import threading
import time


class Spinner:
    __default_spinner_symbols_list = ['|-----|', '|#----|', '|-#---|', '|--#--|', '|---#-|', '|----#|']

    def __init__(self, spinner_symbols_list: [str] = None):
        spinner_symbols_list = spinner_symbols_list if spinner_symbols_list else Spinner.__default_spinner_symbols_list
        self.__screen_lock = threading.Event()
        self.__spinner = cycle(spinner_symbols_list)
        self.__stop_event = False
        self.__thread = None

    def get_spin(self):
        return self.__spinner

    def start(self, spinner_message: str):
        self.__stop_event = False
        time.sleep(0.3)

        def run_spinner(message):
            while not self.__stop_event:
                print("\r{message} {spinner}".format(message=message, spinner=next(self.__spinner)), end="")
                time.sleep(0.3)

            self.__screen_lock.set()

        self.__thread = threading.Thread(target=run_spinner, args=(spinner_message,), daemon=True)
        self.__thread.start()

    def stop(self):
        self.__stop_event = True
        if self.__screen_lock.is_set():
            self.__screen_lock.wait()
            self.__screen_lock.clear()
            print("\r", end="")

        print("\r", end="")

if __name__ == '__main__':
    import time
    # Testing
    spinner = Spinner()
    spinner.start("Downloading")
    # Make actions
    time.sleep(5) # Simulate a process
    #
    spinner.stop()

0
import sys
def DrowWaitCursor(counter):
    if counter % 4 == 0:
        print("/",end = "")
    elif counter % 4 == 1:
        print("-",end = "")
    elif counter % 4 == 2:
        print("\\",end = "")
    elif counter % 4 == 3:
        print("|",end = "")
    sys.stdout.flush()
    sys.stdout.write('\b') 

这也可以是使用带有参数的函数的另一种解决方案。


0

您可以写'\r\033[K'以清除当前行。以下是从@nos修改的示例。

import sys
import time

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

spinner = spinning_cursor()

for _ in range(1, 10):
    content = f'\r{next(spinner)} Downloading...'
    print(content, end="")
    time.sleep(0.1)
    print('\r\033[K', end="")

对于任何对nodejs感兴趣的人,我也写一个nodejs示例。

function* makeSpinner(start = 0, end = 100, step = 1) {
  let iterationCount = 0;
  while (true) {
    for (const char of '|/-\\') {
      yield char;
    }
  }
  return iterationCount;
}

async function sleep(seconds) {
  return new Promise((resolve) => {
    setTimeout(resolve, seconds * 1000);
  });
}

(async () => {
  const spinner = makeSpinner();
  for (let i = 0; i < 10; i++) {
    content = `\r${spinner.next().value} Downloading...`;
    process.stdout.write(content);
    await sleep(0.1);
    process.stdout.write('\r\033[K');
  }
})();


0

我大约一个星期前才刚开始使用python,并发现了此信息。我将在这里找到的内容与在其他地方了解到的有关线程和队列的知识相结合,以提供更好的实现。在我的解决方案中,写入屏幕是由检查内容队列的线程处理的。如果该队列中有内容,则游标旋转线程知道会停止。在另一方面,游标旋转线程将队列用作锁,因此打印线程知道在完成完整的旋转代码后才进行打印。这样可以防止出现争用情况,并防止人们使用过多的代码来保持控制台的清洁。

见下文:

import threading, queue, itertools, sys, time # all required for my version of spinner
import datetime #not required for spinning cursor solution, only my example

console_queue = queue.Queue() # this queue should be initialized before functions
screenlock = queue.Queue()    # this queue too...


def main():
    threading.Thread(target=spinner).start()
    threading.Thread(target=consoleprint).start()

    while True:
        # instead of invoking print or stdout.write, we just add items to the console_queue
        # The next three lines are an example of my code in practice.
        time.sleep(.5) # wait half a second
        currenttime = "[" + datetime.datetime.now().strftime("%d/%m/%Y %H:%M:%S") + "] "
        console_queue.put(currenttime) # The most important part.  Substitute your print and stdout functions with this.


def spinner(console_queue = console_queue, screenlock = screenlock):
    spinnerlist = itertools.cycle(['|', '/', '-', '\\'])
    while True:
        if console_queue.empty():
            screenlock.put("locked")
            sys.stdout.write(next(spinnerlist)) 
            sys.stdout.flush()  
            sys.stdout.write('\b')
            sys.stdout.flush()   
            screenlock.get()
            time.sleep(.1)


def consoleprint(console_queue = console_queue, screenlock = screenlock):
    while True:
        if not console_queue.empty():
            while screenlock.empty() == False:
                time.sleep(.1)
            sys.stdout.flush()
            print(console_queue.get())
            sys.stdout.flush()


if __name__ == "__main__":
    main()

说完我说的所有内容并写完所有内容后,我只做了python一周的工作。如果有更清洁的方法可以这样做,或者我错过了一些我想学习的最佳实践。谢谢。


-1
import requests
import time
import sys

weathercity = input("What city are you in? ")
weather = requests.get('http://api.openweathermap.org/data/2.5/weather?q='+weathercity+'&appid=886705b4c1182eb1c69f28eb8c520e20')
url = ('http://api.openweathermap.org/data/2.5/weather?q='+weathercity+'&appid=886705b4c1182eb1c69f28eb8c520e20')




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


data = weather.json()

temp = data['main']['temp']
description = data['weather'][0]['description']
weatherprint ="In {}, it is currently {}°C with {}."
spinner = spinning_cursor()
for _ in range(25):
    sys.stdout.write(next(spinner))
    sys.stdout.flush()
    time.sleep(0.1)
    sys.stdout.write('\b')

convert = int(temp - 273.15)
print(weatherprint.format(weathercity, convert, description))

请对我好一点。我是新来的。我今年12岁。所以我不能逻辑地思考,但这一定会为您提供帮助。

您将在此处获得摄氏温度。请检查情况如何。通过在此处

1
这是一个精确的复制/粘贴[def spinning_cursor()...sys.stdout.write(next(spinner)) ....在代码]号的9岁的答案。请不要复制(部分)其他人的答案并将其作为自己的答案传递。并且,在回答较旧的问题时,请确保您提供的解决方案比当前答案有所不同,或者至少提供明显更好的解释。
Mohnish
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.