Skip to content

Instantly share code, notes, and snippets.

@xavierskip
Last active August 29, 2015 14:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save xavierskip/3a56664df4524eb01ca8 to your computer and use it in GitHub Desktop.
Save xavierskip/3a56664df4524eb01ca8 to your computer and use it in GitHub Desktop.
summary.py
#!/usr/bin/env python
#coding: utf-8
import sys
argvs = sys.argv
class syntaxError(Exception):
def __init__(self, line):
# start with 1
self.line = line+1
def __str__(self):
return "\nFile line %d, Invalid file syntax" %self.line
class commandError(Exception):
def __init__(self, file):
self.file = file
def __str__(self):
return "usage: python %s -[a|f|s] | -u <username> file_path" %self.file
def readFile(path):
with open(path,'r') as f:
return f.read()
def main():
try:
command = argvs[1]
except IndexError as e:
raise commandError(argvs[0])
exit()
if command == '-a':
try:
path = argvs[2]
except IndexError as e:
raise commandError(argvs[0])
content = readFile(path)
if not content:
print "No printing users"
exit()
lines = content.splitlines()
print "Printing users:"
users = []
for n,line in enumerate(lines):
try:
u = line.split(',')[2].strip()
except IndexError as e:
raise syntaxError(n)
if u not in users:
users.append(u)
for u in users:
print u
elif command == '-f':
try:
path = argvs[2]
except IndexError as e:
raise commandError(argvs[0])
content = readFile(path)
lines = content.splitlines()
print "Total number of files printed: %d" %len(lines)
elif command == '-s':
byte = 0
try:
path = argvs[2]
except IndexError as e:
raise commandError(argvs[0])
content = readFile(path)
lines = content.splitlines()
for n,line in enumerate(lines):
try:
byte += int(line.split(',')[1])
except IndexError as e:
raise syntaxError(n)
print "Total number of bytes printed: %d" %byte
elif command == '-u':
files = 0
byte = 0
try:
username = argvs[2]
path = argvs[3]
except IndexError as e:
raise commandError(argvs[0])
content = readFile(path)
lines = content.splitlines()
print "User %s:" %username
for n,line in enumerate(lines):
try:
f,b,u = line.split(',')
except IndexError as e:
raise syntaxError(n)
if u.strip() == username:
files += 1
byte += int(b)
print "Total number of files printed: %d" %files
print "Total number of bytes printed: %d" %byte
else:
print "Invalid command syntax "
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment