It is a very good script language and I start to learn it for system integration purpose. For example, packaging automation, system administration and process monitoring.
Below are some useful functions for memo:
1. Parameter checking:
if(len(sys.argv) != 2):
print 'COMMAND: ERROR'
sys.exit(1)
sys.argv[1]
2. File existence
if(os.path.exists(path) == False):
print "ERROR: %s doesn't exist." %(path)
sys.exit(1)
3. System Call
os.system("cd " + path + "; cvs update -d -P; cd -;")
if(subprocess.call(["tar", "-czvf", tar_package, "sys", "app"]) != 0):
print "ERROR: fail to tar the package %s" %(tar_package)
sys.exit(1)
It seems subprocess is preferable due to portability.
4. Print
print 'copy %s to %s' %(src, dest)
5. File Copy
shutil.copy2(src, dest)
6. Variable Declaration
dev_path = '../..'
7. Environment Variable
os.environ['PLATFORM']
8. File Path Join
os.path.join(path, os.environ['PLATFORM'], "binary")
9. Find file Name with Pattern
files = glob.glob(os.path.join(gui + '/resource/') + '*.' + format)
for file in files:
shutil.copy(file, target_resource)
10. File System Visit Support
It is a very good design to make it flexible to define customized operations on folder.
def remove_CVS(arg, dirname, names):
(head, tail) = os.path.split(dirname)
if(tail == "CVS"):
shutil.rmtree(dirname)
print "%s is removed. " %(dirname)
os.path.walk(package_sys, remove_CVS, "")
No comments:
Post a Comment