Skip to content

Instantly share code, notes, and snippets.

@dgulino
Last active December 29, 2015 08:29
Show Gist options
  • Save dgulino/7644082 to your computer and use it in GitHub Desktop.
Save dgulino/7644082 to your computer and use it in GitHub Desktop.
Outputs a simple average of all numbers, or given a size of numbers to group, will output a running average.
#!/usr/bin/env python
"""$ c=1;while true;do echo $c;let c=$c+1;sleep .5;done | ./avg.py -n 10
5.5
15.5
25.5
..."""
#Copyright 2005 Drew Gulino
##This program is free software; you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by
## the Free Software Foundation; either version 2 of the License, or
## (at your option) any later version.
##
## This program is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
## GNU General Public License for more details.
##
## You should have received a copy of the GNU General Public License
## along with this program; if not, write to the Free Software
## Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
import sys, os, getopt
from getopt import GetoptError
class Avg:
def __init__(self,avg_width,digits,avg_all):
self.avg_width = avg_width
self.total = 0
self.count = 0
self.digits = digits
self.avg_all = avg_all
def readLine(self,fileObj):
bytes = []
while True:
try:
b = fileObj.read()
except IOError, e:
if e.args[0] == sys.errno.EAGAIN:
break
raise
except KeyboardInterrupt:
break
bytes.append(b)
if b == chr(10) or b == chr(13):
# bytes.append(chr(10))
break
if b == chr(3):
sys.exit()
return ''.join(bytes)
def nonBlockingReadAll(self,fileObj):
bytes = []
while True:
try:
b = fileObj.read(1024)
except IOError, e:
if e.args[0] == sys.errno.EAGAIN:
break
raise
bytes.append(b)
if len(b) < 1024:
break
return ''.join(bytes)
def usage(progname):
print "usage: " + progname
version()
print "[-h --help]"
print "[-v --version]"
print "[-n --nums_to_avg] Size of number groups to average (default=all)"
print "[-d --digits] Significant digits to display (default=all)"
def version():
print "version: 1.0.1"
def main(argv, stdout, environ):
avg_width = 0
digits = 0
avg_all = 1
progname = argv[0]
try:
arglist, args = getopt.getopt(argv[1:], "hvn:d:", ["help", "version", "nums_to_avg=", "digits="])
except GetoptError:
print "Invalid Option!"
usage(progname)
return
# Parse command line arguments
for (field, val) in arglist:
if field in ("-h", "--help"):
usage(progname)
return
if field in ("-v", "--version"):
version()
return
if field in ("-n", "--nums_to_avg"):
avg_width = int(val)
avg_all = 0
if field in ("-d", "--digits"):
digits = int(val)
avg = Avg(avg_width,digits,avg_all)
while 1:
# number = sys.input()
# number = sys.nonBlockingReadAll(sys.stdin)
# number = avg.readLine(sys.stdin)
try:
number = sys.stdin.readline()
if not number:
break
number = float(number)
if avg.avg_all == 1:
avg.total += number
avg.count += 1
avg.avg_width += 1
else:
avg.count += 1
avg.total += number
if avg.count < avg.avg_width:
pass
else:
number = avg.total / avg.count
if digits > 0:
number = round(number,digits)
sys.stdout.write(str(number))
sys.stdout.write("\n")
sys.stdout.flush()
avg.total = 0
avg.count = 0
except(ValueError):
sys.stdout.write("Number Value Exception\n")
sys.stdout.flush()
if avg.avg_all == 1:
number = avg.total / avg.count
if digits > 0:
number = round(number,digits)
sys.stdout.write(str(number))
sys.stdout.write("\n")
sys.stdout.flush()
if __name__ == "__main__":
main(sys.argv, sys.stdout, os.environ)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment