最近,在做一个项目时,我不得不重复下面的步骤:
- 使用扩展名.foo转换从源控制系统中一个基本目录结构下所得到的文件。
- 与这些文件的最新副本进行同步。
- 在一个目录中将同一基本目录下其他目录中具有.foo扩展名的文件复制为具有另一个扩展名.bar的文件。
- 从源控制系统删除原始文件。
- 将复制的文件添加到源控制系统。
这本来可以手动或使用shell/perl脚本实现。手动实现的话会花很长时间,而我又不喜欢使用shell/perl脚本,所以我决定使用jython编写。我花了10分钟来写这个脚本,其间我发现了一个极其有用的模块,shutil。该脚本可以进一步改进以便更高效。下面就是我编写的脚本:
import os
import shutil
# define the source control commands here
delete = "p4 delete "
add = "p4 add "
forceSync = "p4 sync -f "
revert = "p4 revert "
def dirwalk(dir):
'''walk a directory tree'''
for f in os.listdir(dir):
fullpath = os.path.join(dir, f)
print "Looking at "+fullpath
if os.path.isdir(fullpath) and not os.path.islink(fullpath):
dirwalk(fullpath)
if os.path.isfile(fullpath):
s = String(fullpath)
work(s, fullpath)
def work(myStr, thePath):
if myStr.endsWith(sys.argv[2]):
# first revert
theStr = String(revert)
cStr = theStr.concat(myStr)
Runtime.getRuntime().exec(cStr)
# now force sync the file
theStr = String(forceSync)
cStr = theStr.concat(myStr)
Runtime.getRuntime().exec(cStr)
# now copy the file to a different extension
_myStr = myStr.replaceAll(sys.argv[2],sys.argv[3])
# copy the file to the new extension
shutil.copy(myStr, _myStr)
# now delete the file from source control
theStr = String(delete)
cStr = theStr.concat(myStr)
Runtime.getRuntime().exec(cStr)
# now add the new file
theStr = String(add)
cStr = theStr.concat(_myStr)
Runtime.getRuntime().exec(cStr)
"""
Usage:
java weblogic.WLST c:/scripts/p4files.py d:/myfiles .foo .bar
This will revert all files under myfiles directory from source control, force sync's the files,
copy the file to the given extension, deletes the file from source control and add the new file
to source control
"""
dirwalk(sys.argv[1])
可以看出,Jython不仅可以用于调入Java对象,还可以调入操作系统进行文件操作,您还可以非常方便地使用大多数python模块。
这只是Jython的众多用途之一。
原文出处:http://dev2dev.bea.com/blog/sghattu/archive/2006/02/jython_is_just.html