'''
Created on Feb 7, 2013
@author: changxue
@summary: personal utils
'''
import os, time, shutil
#current_time = time.strftime('%Y-%m-%d_%H%M', time.localtime(time.time()))
current_time = time.strftime('%Y-%m-%d', time.localtime(time.time()))
logfile = os.path.join('C:\\works\\workload_out\\out', 'workload_%s.log'%current_time)
def _printlog(msg):
with open(logfile, 'a') as f:
f.write('%s\n'%msg)
print msg
def _get_dirname_from_filename(filename):
''' cut out the extension of filename as dir-name, raise Exception if invalid.'''
if os.path.dirname(filename):
filename = os.path.basename(filename)
index = filename.rfind('.')
if index != -1:
return filename[:index]
else:
raise Exception('%s is not a file or without extension\n'%filename)
def _create_dirs(dir_name):
''' if directory of dir_name not exist, create;
else do nothing.'''
if not os.path.exists(dir_name):
os.makedirs(dir_name)
def _execute_cmd(command):
''' execute outer command. Raise Exception when error.'''
if os.system(command) != 0:
raise Exception( "ERROR ON executing command: %s\n" % command )
else:
_printlog( "SUCCESS: %s" % command )
def _exclude(path):
''' a directory named old placed cases which has already processed, generated by method of clean.'''
operate_list = os.listdir(path)
if 'old' in operate_list:
operate_list.remove('old')
return operate_list
def _move_to_old_dir(path):
''' for cleaning up.'''
if os.path.exists(path):
old_dir = os.path.join(path, 'old')
new_dir = os.path.join(old_dir, current_time)
_create_dirs(new_dir)
operate_list = _exclude(path)
for dirname in operate_list:
try:
shutil.move(os.path.join(path, dirname), os.path.join(new_dir, dirname))
_printlog('SUCCESS: move %s into old dir\n'%os.path.join(path, dirname))
except:
_printlog('FAIL at moving: %s'%os.path.join(path, dirname))
continue
def _remove_empty_dirs(path):
from nt import rmdir
for d in os.listdir(path):
if os.path.isdir(d):
try:
rmdir(d)
_printlog('SUCCESS: remove empty directory: %s\n'%os.path.join(path, d))
except:
continue
def _add_files_to_list (path, pattern='.*\.class$'):
''' walk through [path], find the specified [pattern] files and add them into [result_list]. '''
import re
result_list = []
for root, dirs, files in os.walk (path):
for name in files:
full_name = os.path.join (root, name)
if (re.match (pattern, full_name)):
result_list.append (full_name)
return result_list