How to better control print and stdout? (thanx)

Drew Smathers drew.smathers at earthlink.net
Thu Mar 13 19:19:31 EST 2003


Thanks to Jeff Epler, Erik Max Francis, Donn Cave and Peter Hansen.  All of your suggestions were very helpful.  Okay so here's my finished code (an amalgamation of everyone's ideas).  Any further observations or even critisms would be much appreciated  (by the way, what exactly is the difference between range and xrange?):

#!/usr/bin/env python
import sys, time

def output(char):
	sys.stdout.write(char); sys.stdout.flush()

def spinner(rotations, interval, message=''):
	for x in xrange(rotations):
		output(message + '|/-\\'[x%4] + '\r')
		time.sleep(interval)
	output(' ')
	for i in xrange(len(message)): print ' ',
	output('\r')

def countdown(count, message=''):
	for x in xrange(count,0,-1):
		output(message + str(x) + '   \r')
		time.sleep(1)
	output('Done!')
	for i in xrange(len(message)): print ' ',
	output('\n')
	
	
if __name__ == '__main__':
	usage = '''Usage: counter.py spin rotations interval [message]
       counter.py count integer [message]'''
	try:						
		if sys.argv[1] == 'spin':
			if len(sys.argv) == 5:
				spinner(int(sys.argv[2]), 
				        float(sys.argv[3]), 
						  message=str(sys.argv[4]))
			elif len(sys.argv) == 4:
				spinner(int(sys.argv[2]),
						  float(sys.argv[3]))
			else: print usage	
		elif sys.argv[1] == 'count':
			if len(sys.argv) == 4:
				countdown(int(sys.argv[2]),message=str(sys.argv[3]))
			elif len(sys.argv) == 3:
			   countdown(int(sys.argv[2]))
			else: print usage	
		else:
			print usage
	except KeyboardInterrupt: pass		
	except: print usage		

 


-------Original Message-------
From: Peter Hansen <peter at engcorp.com>
Sent: 03/14/03 06:54 PM
To: python-list at python.org
Subject: Re: How to better control print and stdout?

> 
> Drew Smathers wrote:
> 
> Basically, all I want to do is be able to make nice 
> countdowns, or the classic spinner (|,/,-,\), using the escape 
> code '\b'.
> Is there anyway to get around this without using any fancy libs like
ncurses?

Based on Erik Max's suggestions:


import sys, time

def output(char):
    sys.stdout.write(char)
    sys.stdout.flush()

def spinner(rotations, interval):
    symbols = '|/-\\'
    for x in xrange(rotations):
        for ch in symbols:
            output(ch + '\b')
            time.sleep(interval)
    output(' \n')

if __name__ == '__main__':
    spinner(int(sys.argv[1]), float(sys.argv[2]))

c:\> python spins.py 55 .05

(outputs |/-\ etc....)


-Peter
-- 
<a target=_blank
href="http://mail.python.org/mailman/listinfo/python-list">http://mail.python.org/mailman/listinfo/python-list</a>
> 





More information about the Python-list mailing list