Python code for animating a spinning fan to appear in place

I need to print a spinning fan based on this answer using 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 the way I can show a fan, but with a carriage return to show the following.

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

What is the python code for printing characters without moving the caret position?

+4
source share
4 answers

\n (new line) is automatically added by the print statement. A way to avoid this is to end your expression with a comma.

If you want your fan to be on their own line, use:

 print icons[I]+"\r", 

\r represents a 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 careful not to write anything after it except for fan symbols.

Since printing has some other features, you can go with a kshahar suggestion to use sys.stdout.write() .

+3
source

Here is your complete 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 
+3
source
 def spin(): sys.stdout.write('\\') sys.stdout.fflush() time.sleep(1) sys.stdout.write('\b|') 

This is the beginning. print prints newline characters; sys.stdout.write no. The \b character is inverse space, and sometimes fflush is required to fflush buffers when printing incomplete lines. You should be able to extend this method to work with your code quite easily.

+1
source

You can use sys.stdout.write to print without new lines

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

Source: https://habr.com/ru/post/1345271/


All Articles