Use voussoirkit.hms, separate return value from display value.

This commit is contained in:
voussoir 2020-07-16 14:15:35 -07:00
parent 3280b423e4
commit d174bd1f4d

53
kbps.py
View file

@ -11,54 +11,41 @@ import argparse
import sys import sys
from voussoirkit import bytestring from voussoirkit import bytestring
from voussoirkit import hms
def hms_s(hms):
hms = hms.split(':')
seconds = 0
if len(hms) == 3:
seconds += int(hms[0])*3600
hms.pop(0)
if len(hms) == 2:
seconds += int(hms[0])*60
hms.pop(0)
if len(hms) == 1:
seconds += int(hms[0])
return seconds
def s_hms(s):
(minutes, seconds) = divmod(s, 60)
(hours, minutes) = divmod(minutes, 60)
return '%02d:%02d:%02d' % (hours, minutes, seconds)
def kbps(time=None, size=None, kbps=None): def kbps(time=None, size=None, kbps=None):
if [time, size, kbps].count(None) != 1: if [time, size, kbps].count(None) != 1:
raise ValueError('Incorrect number of unknowns') raise ValueError('Incorrect number of unknowns.')
if size is None:
seconds = hms_s(time)
kibs = int(kbps) / 8
size = kibs * 1024
size *= seconds
out = bytestring.bytestring(size)
return out
if time is None: if time is None:
size = bytestring.parsebytes(size) size = bytestring.parsebytes(size)
kilobits = size / 128 kilobits = size / 128
time = kilobits / int(kbps) time = kilobits / int(kbps)
return s_hms(time) return time
if size is None:
seconds = hms.hms_to_seconds(time)
kibs = int(kbps) / 8
size = kibs * 1024
size *= seconds
return size
if kbps is None: if kbps is None:
seconds = hms_s(time) seconds = hms.hms_to_seconds(time)
size = bytestring.parsebytes(size) size = bytestring.parsebytes(size)
kibs = size / 1024 kibs = size / 1024
kilobits = kibs * 8 kilobits = kibs * 8
kbps = kilobits / seconds kbps = kilobits / seconds
kbps = '%d kbps' % int(round(kbps))
return kbps return kbps
def example_argparse(args): def kbps_argparse(args):
print(kbps(time=args.time, size=args.size, kbps=args.kbps)) result = kbps(time=args.time, size=args.size, kbps=args.kbps)
if args.time is None:
print(hms.seconds_to_hms(time))
if args.size is None:
print(bytestring.bytestring(size))
if args.kbps is None:
print('%d kbps' % round(result))
def main(argv): def main(argv):
parser = argparse.ArgumentParser() parser = argparse.ArgumentParser()
@ -66,7 +53,7 @@ def main(argv):
parser.add_argument('-t', '--time', dest='time', default=None) parser.add_argument('-t', '--time', dest='time', default=None)
parser.add_argument('-s', '--size', dest='size', default=None) parser.add_argument('-s', '--size', dest='size', default=None)
parser.add_argument('-k', '--kbps', dest='kbps', default=None) parser.add_argument('-k', '--kbps', dest='kbps', default=None)
parser.set_defaults(func=example_argparse) parser.set_defaults(func=kbps_argparse)
args = parser.parse_args(argv) args = parser.parse_args(argv)
return args.func(args) return args.func(args)