options for selecting excludes

This commit is contained in:
Ville Rantanen
2020-09-29 11:06:06 +03:00
parent 2f4cfd196f
commit cc7397e78b

View File

@@ -1,4 +1,4 @@
#!/usr/bin/env python #!/usr/bin/env python3
import sys,os,glob import sys,os,glob
from datetime import datetime from datetime import datetime
@@ -7,7 +7,7 @@ import re,signal,time
import subprocess import subprocess
#,threading #,threading
VERSION=2 VERSION=3
W= '30' W= '30'
R= '31' R= '31'
@@ -40,21 +40,24 @@ Shows the output of df in colour.
parser.add_argument("--no-colors",'--nc',action="store_false",dest="colors",default=True, parser.add_argument("--no-colors",'--nc',action="store_false",dest="colors",default=True,
help="Disable colored output") help="Disable colored output")
parser.add_argument("-n",type=int,dest="delay",default=3, parser.add_argument("-n",type=int,dest="delay",default=3,
help="Refresh delay") help="Refresh delay")
parser.add_argument("-1",action="store_true",dest="once",default=False, parser.add_argument("-1",action="store_true",dest="once",default=False,
help="Run once and exit") help="Run once and exit")
parser.add_argument("-x",'--exclude',type=str,dest="exclude",default="tmpfs,devtmpfs,squashfs",
help="Comma separated list of excluded filesystem types. Defaults: %(default)s")
parser.add_argument("--version",action='version', version=VERSION) parser.add_argument("--version",action='version', version=VERSION)
options=parser.parse_args() options=parser.parse_args()
return options return options
def c(attribs): def c(attribs):
''' ANSI colorizer ''' ''' ANSI colorizer '''
if not options.colors: if not options.colors:
return "" return ""
return '\033['+';'.join(attribs)+'m' return '\033['+';'.join(attribs)+'m'
def pos(y,x): def pos(y,x):
''' ANSI absolute position set ''' ''' ANSI absolute position set '''
return "\033["+str(y)+";"+str(x)+"H" return "\033["+str(y)+";"+str(x)+"H"
@@ -71,7 +74,7 @@ def colorize(string):
def count_running(string, stats): def count_running(string, stats):
''' Counts the running executions ''' ''' Counts the running executions '''
spl=[i for i in " ".join(string.split()).split(' ')] spl=[i for i in " ".join(string.split()).split(' ')]
if len(spl)!=7: if len(spl)!=7:
return stats return stats
@@ -97,18 +100,19 @@ def count_running(string, stats):
int(spl[2])*1024 int(spl[2])*1024
)) ))
stats['running'].sort(key=SORTKEY) stats['running'].sort(key=SORTKEY)
stats['files']=[i[2] for i in stats['running']] stats['files']=[i[2] for i in stats['running']]
totalfree=sum([i[0] for i in stats['running']]) totalfree=sum([i[0] for i in stats['running']])
total=sum([i[6] for i in stats['running']]) total=sum([i[6] for i in stats['running']])
stats['totals']=[totalfree, total] stats['totals']=[totalfree, total]
return stats return stats
class EndProgram( Exception ): class EndProgram( Exception ):
''' Nice way of exiting the program ''' ''' Nice way of exiting the program '''
pass pass
def is_number(s): def is_number(s):
''' Check if string is float ''' ''' Check if string is float '''
try: try:
@@ -117,6 +121,7 @@ def is_number(s):
except: except:
return False return False
def str_short(s,stats): def str_short(s,stats):
''' shorten text to fit screen ''' ''' shorten text to fit screen '''
maxL=stats['size'][1] - 16 maxL=stats['size'][1] - 16
@@ -125,7 +130,7 @@ def str_short(s,stats):
spl=s.split('/') spl=s.split('/')
sNew=spl[0]+'/...'+'/'.join(spl[1:])[-(maxL-len(spl[0])-5):] sNew=spl[0]+'/...'+'/'.join(spl[1:])[-(maxL-len(spl[0])-5):]
return sNew return sNew
def print_stats(stats): def print_stats(stats):
''' Prints logged errors, and the status line ''' ''' Prints logged errors, and the status line '''
@@ -157,10 +162,11 @@ def print_stats(stats):
CLRLN) CLRLN)
for i in range(stats['size'][0]-7-len(stats['running'])): for i in range(stats['size'][0]-7-len(stats['running'])):
sys.stdout.write(pos(e+5+ex[0]+i,0)+" "+CLRLN) sys.stdout.write(pos(e+5+ex[0]+i,0)+" "+CLRLN)
sys.stdout.write(DOWN+CLRBLN+CLRLN) sys.stdout.write(DOWN+CLRBLN+CLRLN)
#sys.stdout.write(LOAD) #sys.stdout.write(LOAD)
def print_stats_once(stats): def print_stats_once(stats):
''' Prints logged errors, once ''' ''' Prints logged errors, once '''
e=0 e=0
@@ -182,12 +188,12 @@ def print_stats_once(stats):
CLRLN+'\n') CLRLN+'\n')
sys.stdout.write( sys.stdout.write(
' '.join([ ' '.join([
human_size(stats['totals'][1]).rjust(8), human_size(stats['totals'][1]).rjust(8),
human_size(stats['totals'][1]-stats['totals'][0]).rjust(10), ' ', human_size(stats['totals'][1]-stats['totals'][0]).rjust(10), ' ',
human_size(stats['totals'][0]).rjust(10) human_size(stats['totals'][0]).rjust(10)
])+ ])+
CLRLN+'\n') CLRLN+'\n')
def colorize_usage(string): def colorize_usage(string):
''' colorizes the usage string ''' ''' colorizes the usage string '''
@@ -210,11 +216,13 @@ def mean_speed(history):
speed=sum(history)/len(history) speed=sum(history)/len(history)
return int(speed) return int(speed)
def human_time(dt=False): def human_time(dt=False):
if not dt: if not dt:
dt=datetime.now() dt=datetime.now()
return dt.strftime("%H:%M:%S") return dt.strftime("%H:%M:%S")
def human_size(size,precision=1): def human_size(size,precision=1):
if size==None: if size==None:
return 'nan' return 'nan'
@@ -231,6 +239,7 @@ def human_size(size,precision=1):
defPrecision=precision defPrecision=precision
return "%s%.*f%s"%(sign,defPrecision,size,suffixes[suffixIndex]) return "%s%.*f%s"%(sign,defPrecision,size,suffixes[suffixIndex])
def readinput(lf): def readinput(lf):
try: try:
line = lf.stdout.readline() line = lf.stdout.readline()
@@ -239,6 +248,7 @@ def readinput(lf):
except: except:
return "CleanerTimeout" return "CleanerTimeout"
def termsize(): def termsize():
try: try:
rows, columns = os.popen('stty size', 'r').read().split() rows, columns = os.popen('stty size', 'r').read().split()
@@ -255,7 +265,7 @@ color_match={#'line_ends':(re.compile('$'),c.END),
'percent':(re.compile('([0-9]+%)'),c([Y,S])+'\\1'+c([E])), 'percent':(re.compile('([0-9]+%)'),c([Y,S])+'\\1'+c([E])),
} }
stats={'time':datetime.now(), stats={'time':datetime.now(),
'running':[], 'running':[],
'files':[], 'files':[],
'totals':[], 'totals':[],
@@ -265,19 +275,23 @@ stats={'time':datetime.now(),
if not options.once: if not options.once:
sys.stdout.write(CLR+pos(0,0)+"Launching...") sys.stdout.write(CLR+pos(0,0)+"Launching...")
omit_opts = []
for omit in options.exclude.split(","):
omit_opts.append("-x")
omit_opts.append(omit.strip())
while 1: while 1:
try: try:
proc = subprocess.Popen(['df','-x','tmpfs','-x','devtmpfs','-T'],stdout=subprocess.PIPE) proc = subprocess.Popen(['df','-T'] + omit_opts,stdout=subprocess.PIPE)
# set a 5 second timeout for the line read. # set a 5 second timeout for the line read.
#~ signal.signal(signal.SIGALRM, transfers.readline) #~ signal.signal(signal.SIGALRM, transfers.readline)
#~ signal.alarm(5) #~ signal.alarm(5)
stdout,stderr=proc.communicate() stdout,stderr=proc.communicate()
if not stdout: if not stdout:
raise EndProgram raise EndProgram
for line in stdout.split('\n')[1:]: for line in stdout.decode('utf-8').split('\n')[1:]:
stats=count_running(line,stats) stats=count_running(line,stats)
if options.once: if options.once:
@@ -286,11 +300,11 @@ while 1:
print_stats(stats) print_stats(stats)
sys.stdout.flush() sys.stdout.flush()
time.sleep(options.delay) time.sleep(options.delay)
except EndProgram,KeyboardInterrupt: except (EndProgram, KeyboardInterrupt):
sys.stdout.write(DOWN+'\n') sys.stdout.write(DOWN+'\n')
sys.stdout.flush() sys.stdout.flush()
sys.exit(0) sys.exit(0)