开发者

Python code to animate a rotating fan to appear in place

I need to print out rotating fan based on this answer with Python.

import threading
import subprocess

I = 0

class RepeatingTimer(threading._Timer):
    def run(self):
        while True:
            self.finished.wait(self.interval)
            if self.finished.is_set():
                return
            else:
                self.function(*self.args, **self.kwargs)


def status():
    global I
    icons = ['|','/','--','\\']
    print icons[I]
    I += 1
    if I == 4: I = 0

timer = RepeatingTimer(1.0, status)
timer.daemon = True # Allows program to exit if only the thread is alive
timer.start()

proc = subprocess.Popen([ 'python', "wait.py" ])
proc.wait()

timer.cancel()

This code works as I can show the fan, but with carriage return to show as follows.

|
/
--
\
|
/
--
...

What's the python code to print the characters without mo开发者_Go百科ving the caret position?


\n (new line) is automatically inserted by your print statement. The way to avoid it is to end your statement with a comma.

If you want your fan to be on a line on it's own, use:

print icons[I]+"\r",

\r represents the carriage return.

If you want your fan to be at the end of a non-empty line, use \b for the backspace character:

print icons[I]+"\b",

but be wary of not writing anything other than the fan characters after it.

Since print has got some other peculiarities, you may want to go with kshahar suggestion of using sys.stdout.write().


Here is your total solution:

import itertools
import sys
import time

def whirl(max=50):
    parts = ['|', '/', '-', '\\']

    cnt = 1
    for part in itertools.cycle(parts):
        if cnt >= max:
            break
        sys.stdout.write(part)
        sys.stdout.flush()
        time.sleep(.1)
        sys.stdout.write('\b')
        cnt += 1


def spin():
    sys.stdout.write('\\')
    sys.stdout.fflush()
    time.sleep(1)
    sys.stdout.write('\b|')

That's a start. print prints newlines; sys.stdout.write doesn't. The \b character is a backspace, and fflush is sometimes necessary to flush buffers when printing incomplete lines. You should be able to extend this method to work with your code pretty easily.


You could use sys.stdout.write to print without the new lines

sys.stdout.write(icons[I])
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜