Python 如何创建一个旋转的命令行光标?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4995733/
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
How to create a spinning command line cursor?
提问by Nathan
Is there a way to print a spinning cursor in a terminal using Python?
有没有办法使用 Python 在终端中打印旋转光标?
采纳答案by nos
Something like this, assuming your terminal handles \b
像这样,假设您的终端处理 \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')
回答by Klaus Byskov Pedersen
Sure, it's possible. It's just a question of printing the backspace character (\b) in between the four characters that would make the "cursor" look like it's spinning ( -, \, |, /).
当然,这是可能的。这只是\b在四个字符之间打印退格字符 ( ) 的问题,这将使“光标”看起来像在旋转 ( -, \, |, /)。
回答by Nathan
A solution:
一个办法:
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)
The key is to use the backspace character '\b' and flush stdout.
关键是使用退格字符 '\b' 并刷新标准输出。
回答by David
For more advanced console manipulations, on unix you can use the curses python module, and on windows, you can use WConiowhich provides equivalent functionality of the curses library.
对于更高级的控制台操作,在 unix 上你可以使用curses python 模块,在windows 上你可以使用WConio,它提供了curses 库的等效功能。
回答by David
#!/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()
CAVEATS:In my experience this doesn't work in all terminals. A more robust way to do this under Unix/Linux, be it more complicated is to use the cursesmodule, which doesn't work under Windows. You probably want to slow it down some how with actual processing that is going on in the background.
警告:根据我的经验,这不适用于所有终端。在 Unix/Linux 下执行此操作的一种更可靠的方法是使用更复杂的Curses模块,该模块在 Windows 下不起作用。您可能希望通过在后台进行的实际处理来减慢它的速度。
回答by MattiaG
curses module.i'd have a look at the addstr() and addch() functions. Never used it though.
诅咒模块。我想看看 addstr() 和 addch() 函数。虽然从来没有用过。
回答by Beni Cherniavsky-Paskin
Grab the awesome progressbarmodule - http://code.google.com/p/python-progressbar/use RotatingMarker.
获取很棒的progressbar模块 - http://code.google.com/p/python-progressbar/use RotatingMarker。
回答by Damien
A nice pythonic way is to use itertools.cycle:
一个不错的 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
Also, you might want to use threading to display the spinner during a long function call, as in http://www.interclasse.com/scripts/spin.php
此外,您可能希望在长时间的函数调用期间使用线程来显示微调器,如http://www.interclasse.com/scripts/spin.php
回答by user3297919
import sys
def DrowWaitCursor(self, 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')
This can be also another solution using a function with a parameter.
这也可以是使用带参数的函数的另一种解决方案。
回答by Victor Moyseenko
Easy to use API (this will run the spinner in a separate thread):
易于使用的 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
Now use it in a withblock anywhere in the code:
现在with在代码的任何位置的块中使用它:
with Spinner():
# ... some long-running operations
# time.sleep(3)

