77class Spinner (object ):
88 spinner_cycle = itertools .cycle (['-' , '/' , '|' , '\\ ' ])
99
10- def __init__ (self , beep = False , disable = False , force = False ):
10+ def __init__ (self , beep = False , disable = False , force = False , stream = sys . stdout ):
1111 self .disable = disable
1212 self .beep = beep
1313 self .force = force
14+ self .stream = stream
1415 self .stop_running = None
1516 self .spin_thread = None
1617
1718 def start (self ):
1819 if self .disable :
1920 return
20- if sys . stdout .isatty () or self .force :
21+ if self . stream .isatty () or self .force :
2122 self .stop_running = threading .Event ()
2223 self .spin_thread = threading .Thread (target = self .init_spin )
2324 self .spin_thread .start ()
@@ -29,11 +30,11 @@ def stop(self):
2930
3031 def init_spin (self ):
3132 while not self .stop_running .is_set ():
32- sys . stdout .write (next (self .spinner_cycle ))
33- sys . stdout .flush ()
33+ self . stream .write (next (self .spinner_cycle ))
34+ self . stream .flush ()
3435 time .sleep (0.25 )
35- sys . stdout .write ('\b ' )
36- sys . stdout .flush ()
36+ self . stream .write ('\b ' )
37+ self . stream .flush ()
3738
3839 def __enter__ (self ):
3940 self .start ()
@@ -44,12 +45,12 @@ def __exit__(self, exc_type, exc_val, exc_tb):
4445 return False
4546 self .stop ()
4647 if self .beep :
47- sys . stdout .write ('\7 ' )
48- sys . stdout .flush ()
48+ self . stream .write ('\7 ' )
49+ self . stream .flush ()
4950 return False
5051
5152
52- def spinner (beep = False , disable = False , force = False ):
53+ def spinner (beep = False , disable = False , force = False , stream = sys . stdout ):
5354 """This function creates a context manager that is used to display a
5455 spinner on stdout as long as the context has not exited.
5556
@@ -73,7 +74,7 @@ def spinner(beep=False, disable=False, force=False):
7374 do_something_else()
7475
7576 """
76- return Spinner (beep , disable , force )
77+ return Spinner (beep , disable , force , stream )
7778
7879
7980from ._version import get_versions
0 commit comments