dev2dev.bea.com.cn
首页 资源中心 dev2dev学堂 在线技术论坛 专家Blog User Group CodeShare

Jython相当有用

2006-03-28 00:00:00 | 评论 (0) | 被访问(1332)次

Satya Ghattu
  Satya Ghattu加入BEA公司已经有4年多了,担任软件工程师,专门负责WebLogic Platform的Operations Administration以及Management方面。Satya拥有将近8年的软件开发经验,主要是在应用服务器、核心java以及相关的(J2EE)技术方面。他还领导着dev2dev上CodeShare中的几个开源项目,并向dev2dev社区贡献了大量的代码示例。Satya是WebLogic Scripting Tool (WLST)的最初设计者,该工具是BEA官方支持的WebLogic Server命令行工具。在加入BEA之前,他曾在许多软件公司担任各种不同的职务,做过高级Java开发人员、软件分析师,还做过Oracle数据库管理员。Satya持有俄亥俄州Akron大学的工程学硕士学位。


  最近,在做一个项目时,我不得不重复下面的步骤:

  1. 使用扩展名.foo转换从源控制系统中一个基本目录结构下所得到的文件。
  2. 与这些文件的最新副本进行同步。
  3. 在一个目录中将同一基本目录下其他目录中具有.foo扩展名的文件复制为具有另一个扩展名.bar的文件。
  4. 从源控制系统删除原始文件。
  5. 将复制的文件添加到源控制系统。

  这本来可以手动或使用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



Tags: Jython script 脚本
文章评论:(以下网友留言只代表个人观点,不代表BEA观点和立场)
暂时没有评论!

2006年03月

    1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30 31    
             
RSS订阅

Satya Ghattu's Blog搜索