python如何使用jt400.jar包代码实例


Posted in Python onDecember 20, 2019

这篇文章主要介绍了python如何使用jt400.jar包代码实例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下

代码如下

jt400helper.py

#coding=utf-8
import jpype
import os



class JT400Helper(object):
  def __init__(self, server,username,pwd):
    jvmpath=r"C:\Program Files\Java\jre1.8.0_60\bin\server\jvm.dll"
    jarpath=r'd:\temp\jt400.jar'
    jvmArg = "-Djava.class.path=%s" % jarpath
    jpype.startJVM(jvmpath,jvmArg)
    
    #jt400
    AS400=jpype.JClass('com.ibm.as400.access.AS400')
    CommandCall=jpype.JClass('com.ibm.as400.access.CommandCall')
    ProgramCall=jpype.JClass('com.ibm.as400.access.ProgramCall')
    SpooledFileList=jpype.JClass('com.ibm.as400.access.SpooledFileList')
    AS400Text=jpype.JClass('com.ibm.as400.access.AS400Text')
    AS400JDBCDriver=jpype.JClass('com.ibm.as400.access.AS400JDBCDriver')
    
    
    
    #java
    Connection=jpype.JClass('java.sql.Connection')
    DatabaseMetaData=jpype.JClass('java.sql.DatabaseMetaData')
    Statement=jpype.JClass('java.sql.Statement')
    self.ResultSet=jpype.JClass('java.sql.ResultSet')
    
    self.server,self.username,self.pwd = server,username,pwd
    self.RJobLog=jpype.JClass('com.ibm.as400.resource.RJobLog')
    self.AS400FTP=jpype.JClass('com.ibm.as400.access.AS400FTP')
    self.IFSFile=jpype.JClass('com.ibm.as400.access.IFSFile')
    self.ObjectDescription=jpype.JClass('com.ibm.as400.access.ObjectDescription')
    
    self.ProgramParameter=jpype.JClass('com.ibm.as400.access.ProgramParameter')
    self.DriverManager=jpype.JClass('java.sql.DriverManager')
    self.DriverManager.registerDriver(AS400JDBCDriver())
    
    
    self.system=AS400(server,username,pwd)
    self.cc=CommandCall(self.system)
    self.outqueue = SpooledFileList(self.system)
    self.pc = ProgramCall(self.system)
  
  def ShowIfs(self,ifspath):
    ifs=self.IFSFile(self.system,ifspath)
    print 'exists : ',ifs.exists()
    print 'isDirectory : ',ifs.isDirectory()
    print 'isFile : ',ifs.isFile()
    fs=ifs.listFiles()
    if len(fs)>0:
      for f in fs:
        print f.name
  
  def ShowObj2(self,lib,obj):
    od = self.ObjectDescription(system,lib,obj,"FILE")
    print od.CHANGE_DATE_AND_TIME
  
  def ShowObj(self,lib,obj,tmplib):
    cmdstr = "DSPOBJD OBJ(%s/%s) OBJTYPE(*PGM) OUTPUT(*OUTFILE) OUTFILE(%s/OBJD)" % (lib,obj,tmplib)
    msg = self.GetCmdMsg(cmdstr)
    if msg == "":
      cmdstr = "SELECT ODLBNM, ODOBNM, ODOBTP, ODOBAT,ODOBSZ , ODOBTX, ODLDAT, ODLTIM, ODOBSY, ODCRTU, ODJRST, ODJRNM, ODJRLB, ODJRIM, ODJREN,ODJRCN, ODJRDT, ODJRTI FROM %s.objd" % tmplib
      self.GetSQLResult(cmdstr)    
  
  def SaveFieldDef(self,flib,file,tmplib,ofile):
    cmdstr = "DSPFFD FILE(%s/%s) OUTPUT(*OUTFILE) OUTFILE(%s/FIELDDEF)" % (flib,file,tmplib)
    msg = self.GetCmdMsg(cmdstr)
    if msg == "":
      cmdstr = "SELECT WHFLDI, WHFTXT, WHFLDT, WHFLDD, WHFLDP,WHFLDB, WHFOBO FROM %s.FIELDDEF WHERE WHFLDI <> ' ' ORDER BY WHFOBO" % tmplib
      self.GetSQLResult(cmdstr,ofile)
  
  def SaveJobLog(self,jobstr,ofile):
    msg = self.GetJobLog(jobstr)
    with open(ofile,'w') as f:
      f.write(msg)
  
  def GetJobLog(self,jobstr):
    jobarr = jobstr.split('/')
    jobnum,jobuser,jobname=jobarr[0],jobarr[1],jobarr[2]
    return self.GetJobLogByNum(jobnum,jobuser,jobname)
    
  def GetJobLogByNum(self,jobnum,jobuser,jobname):
    joblog=self.RJobLog(self.system,jobname,jobuser,jobnum)
    joblog.open()
    joblog.waitForComplete()
    num=joblog.getListLength()
    msgs = []
    for i in range(0,num):
      qmsg=joblog.resourceAt(i)
      msgs.append(qmsg.getAttributeValue("MESSAGE_TEXT"))
    msg = '\n'.join(msgs)
    return msg
  
  
  def GetSQLResult(self,cmdstr,ofile=""):
    connection = self.DriverManager.getConnection("jdbc:as400://" + self.server, self.username, self.pwd)
    dmd = connection.getMetaData()
    select = connection.createStatement(self.ResultSet.TYPE_SCROLL_SENSITIVE,self.ResultSet.CONCUR_UPDATABLE)
    print cmdstr
    rs = select.executeQuery(cmdstr)
    strs = ""
    cols = rs.getMetaData().getColumnCount()
    while (rs.next()):
      rowstrs = []
      for i in range(1,cols+1):
        value = rs.getString(i)
        if ' ' in value:
          value = '"%s"' % value
        rowstrs.append(rs.getString(i))
      strs+=','.join(rowstrs)+'\n'
    connection.close();
    if ofile <> "":
      with open(ofile,'w') as f:
        f.write(strs)
    else:
      print strs
    
   
  def CallProgram(self,plib,pgm,paras):
    #WRKACTJOB SBS(QUSRWRK) JOB(QZRCSRVS) - dump not work
    #paras=["Y","12345","   "]  
    pgmparas=[]
    for para in paras:
      pgmparas.append(ProgramParameter(para))
      print str(pgmparas.getInputData())
    self.pc.setProgram("/QSYS.LIB/%s.LIB/%s.PGM" % (plib,pgm),pgmparas)
    successfully = self.pc.run()
    msg = ''
    job = pc.getJob()
    print pc.toString()
    print job.toString()
    if successfully <> True:
      ml=self.pc.getMessageList()
      for m in ml:
        msg += m.getText() +'\n'
      print msg
      self.system.disconnectAllServices()
    return msg
    
  def GetCmdMsg(self,cmdstr):
    msg = ''
    print cmdstr
    successfully = self.cc.run(cmdstr)
    if successfully <> True:
      ml=self.cc.getMessageList()
      for m in ml:
        msg += m.getText() +'\n'
      print msg
    return msg
  
  def CheckObjExists(self,lib,file,type="*FILE"):
    str = "CHKOBJ OBJ(%s/%s) OBJTYPE(%s)" % (lib,file,type)
    return self.GetCmdMsg(str)

  def DeleteObj(self,lib,file):  
    str = "DLTF FILE(%s/%s)" % (lib,file)
    return self.GetCmdMsg(str)
    
    
  def FileToIfs(self,lib,file,mem,ifspath):
    # don't use RMVBLANK(*TRAILING) ,will cause numeric field contains blank characters error when put ifs to file
    str = "CPYTOIMPF FROMFILE(%s/%s %s) TOSTMF('%s') MBROPT(*REPLACE) STMFCCSID(*STMF) RCDDLM(*CRLF) DTAFMT(*DLM) STRDLM(*NONE)" % (lib,file,mem,ifspath)
    print lib,file,mem,"->",ifspath
    return self.GetCmdMsg(str)
    
  def IfsToFile(self,ifspath,lib,file,mem):
    str = "CPYFRMIMPF FROMSTMF('%s') TOFILE(%s/%s %s) MBROPT(*REPLACE) RCDDLM(*CRLF) STRDLM(*NONE) FLDDLM(',') ERRRCDOPT(*REPLACE) RPLNULLVAL(*FLDDFT)" % (ifspath,lib,file,mem)
    print ifspath,"->",lib,file,mem
    return self.GetCmdMsg(str)
    
  def FileToPc(self,lib,file,mem,ofile):
    tmpifs = "QDLS/TEMP/%s.CSV" % mem
    self.FileToIfs(lib,file,mem,tmpifs)
    self.FtpGetIfsFile(tmpifs,ofile)
  
  def PcToFile(self,ifile,lib,file,mem):
    tmpifs = "QDLS/TEMP/%s.CSV" % mem
    self.FtpPutIfsFile(ifile,tmpifs)
    self.IfsToFile(tmpifs,lib,file,mem)
    

  def FtpGetIfsFile(self,ifspath,ofile):
    ftp=self.AS400FTP(self.system)
    successfully = ftp.get(ifspath,ofile)
    print ifspath,"->",ofile
    return successfully
    
  def FtpGetText(self,lib,srcf,mem,dest=r"d:\temp"):
    ftp=self.AS400FTP(self.system)
    target="/QSYS.LIB/%s.LIB/%s.FILE/%s.MBR" % (lib,srcf,mem)
    if os.path.isdir(dest):
      dest=os.path.join(dest,mem+".txt")
    print target,"->",dest
    successfully = ftp.get(target,dest)
    return successfully
    
  def FtpGetSavf(self,lib,savf,dest=r"d:\temp"):
    ftp=self.AS400FTP(self.system)
    target="/QSYS.LIB/%s.LIB/%s.SAVF" % (lib,savf)
    # QUOTE SITE NAMEFMT 0 QGPL/QCLSRC.TEST
    # QUOTE SITE NAMEFMT 1 /QSYS.lib/Libname.lib/Fname.file/Mname.mbr
    ftp.issueCommand("quote site namefmt 1")
    if os.path.isdir(dest):
      dest=os.path.join(dest,savf+".SAVF")
    # can not get it if not set data transfer type
    ftp.setDataTransferType(1)
    successfully = ftp.get(target,dest)
    return successfully
   
  
  def FtpPutIfsFile(self,ifile,ifspath):
    ftp=self.AS400FTP(self.system)
    successfully = ftp.put(ifile,ifspath)
    print ifile,"->",ifspath
    return successfully
       
  def FtpPutText(self,ifile,lib,srcf,mem):
    ftp=self.AS400FTP(self.system)
    dest="/QSYS.LIB/%s.LIB/%s.FILE/%s.MBR" % (lib,srcf,mem)
    successfully = ftp.put(ifile,dest)
    print ifile,"->",lib,srcf,mem
    return successfully
  
  def GetOutQList(self,outqlib,outq):
    print "OutQueue : %s/%s" % (outqlib,outq)
    self.outqueue.setQueueFilter("/QSYS.LIB/%s.LIB/%s.OUTQ" % (outqlib,outq))
    self.outqueue.setUserFilter("*ALL")
    self.outqueue.openSynchronously()
    enums=self.outqueue.getObjects()
    i = 1
    info = ""
    while (enums.hasMoreElements()):
      splf=enums.nextElement()
      if(splf<>None):
        strs=[]
        strs.append("System :%s , File : %s , File Number : %s , Progarm :%s , Date : %s" % (splf.getStringAttribute(271),splf.getStringAttribute(104),splf.getIntegerAttribute(105).toString(),splf.getStringAttribute(272),splf.getStringAttribute(34)))
        strs.append("Number/User/Job : %s/%s/%s" % (splf.getStringAttribute(60),splf.getStringAttribute(62),splf.getStringAttribute(59)))
        strs.append("File Pages: %s , Print quality : %s , Printer device type : %s , Page size length : %d " % (splf.getIntegerAttribute(111).toString(),splf.getStringAttribute(48),splf.getStringAttribute(90),splf.getFloatAttribute(78).intValue()))
        info += '\n'.join(strs)+'\n'
        i+=1
    self.system.disconnectAllServices()
    print "total spool files : ",i
    print info
  
  def GetSpoolFile(self,sflib,sffile,sfname,sfjobnum,fnum,dest):
    if self.CheckObjExists(sflib,sffile)<>"":
      # IGCDTA parameter is for DBCS file
      self.GetCmdMsg("CRTPF FILE(%s/%s) RCDLEN(160) IGCDTA(*YES)" % (sflib,sffile))
    str = "CPYSPLF FILE(%s) TOFILE(%s/%s) JOB(%s) SPLNBR(%d)" % (sfname,sflib,sffile,sfjobnum,fnum)
    msg = self.GetCmdMsg(str)
    if msg == "":
      self.FtpGetText(sflib,sffile,sffile,dest)
      print "download successfully!"
    def PutMsg(self,qlib,qname,msg):    qstr = "/QSYS.LIB/%s.LIB/%s.DTAQ" % (qlib,qname)    dataqueue=self.DataQueue(self.system,qstr)    dataqueue.write(msg)      def GetMsg(self,qlib,qname):    qstr = "/QSYS.LIB/%s.LIB/%s.DTAQ" % (qlib,qname)    dataqueue=self.DataQueue(self.system,qstr)    dqdata = dataqueue.read()    dqdatastr = 'No data'    if dqdata <> None:      dqdatastr = dqdata.getString()    print dqdatastr    return dqdatastr
    
if __name__ == '__main__':
  pass

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持三水点靠木。

Python 相关文章推荐
Python文件右键找不到IDLE打开项解决办法
Jun 08 Python
浅谈python中的变量默认是什么类型
Sep 11 Python
django开发教程之利用缓存文件进行页面缓存的方法
Nov 10 Python
Python及Django框架生成二维码的方法分析
Jan 31 Python
Python的log日志功能及设置方法
Jul 11 Python
在python中用url_for构造URL的方法
Jul 25 Python
关于python 跨域处理方式详解
Mar 28 Python
Python %r和%s区别代码实例解析
Apr 03 Python
浅谈keras 的抽象后端(from keras import backend as K)
Jun 16 Python
keras topN显示,自编写代码案例
Jul 03 Python
详解python模块pychartdir安装及导入问题
Oct 22 Python
基于Python爬取搜狐证券股票过程解析
Nov 18 Python
基于python使用tibco ems代码实例
Dec 20 #Python
使用python实现数组、链表、队列、栈的方法
Dec 20 #Python
python隐藏类中属性的3种实现方法
Dec 19 #Python
Python合并2个字典成1个新字典的方法(9种)
Dec 19 #Python
关于Python中定制类的比较运算实例
Dec 19 #Python
在python中利用try..except来代替if..else的用法
Dec 19 #Python
Python字符串的修改方法实例
Dec 19 #Python
You might like
印尼林东PWN黄金曼特宁咖啡豆:怎么冲世界上最醇厚的咖啡冲煮教程
2021/03/03 冲泡冲煮
PHP实用函数分享之去除多余的0
2015/02/06 PHP
php简单生成随机数的方法
2015/07/30 PHP
Yii核心验证器api详解
2016/11/23 PHP
laravel 解决Validator使用中出现的问题
2019/10/25 PHP
如何用javascript判断录入的日期是否合法
2007/01/08 Javascript
javascript日期格式化示例分享
2014/03/05 Javascript
zeroclipboard 单个复制按钮和多个复制按钮的实现方法
2014/06/14 Javascript
jQuery Mobile开发中日期插件Mobiscroll使用说明
2016/03/02 Javascript
12个非常实用的JavaScript小技巧【推荐】
2016/05/18 Javascript
nodejs微信公众号支付开发
2016/09/19 NodeJs
Actionscript与javascript交互实例程序(修改)
2016/09/22 Javascript
浅谈JavaScript正则表达式-非捕获性分组
2017/03/08 Javascript
解决JS外部文件中文注释出现乱码问题
2017/07/09 Javascript
JavaScript变量类型以及变量作用域详解
2017/08/14 Javascript
jQuery实现每隔一段时间自动更换样式的方法分析
2018/05/03 jQuery
详解vuex中action何时完成以及如何正确调用dispatch的思考
2019/01/21 Javascript
浅谈小程序 setData学问多
2019/02/20 Javascript
[59:48]LGD vs IG 2018国际邀请赛小组赛BO2 第一场 8.18
2018/08/19 DOTA
把项目从Python2.x移植到Python3.x的经验总结
2015/04/20 Python
python导入时小括号大作用
2017/01/10 Python
python抽取指定url页面的title方法
2018/05/11 Python
python保存文件方法小结
2018/07/27 Python
Python设计模式之简单工厂模式实例详解
2019/01/22 Python
python实现比对美团接口返回数据和本地mongo数据是否一致示例
2019/08/09 Python
基于python实现雪花算法过程详解
2019/11/16 Python
Python基于smtplib模块发送邮件代码实例
2020/05/29 Python
初中化学教学反思
2014/01/23 职场文书
寄语十八大感言
2014/02/07 职场文书
农村党支部书记党群众路线四风问题整改措施
2014/09/26 职场文书
关于感谢信的范文
2015/01/23 职场文书
交警失职检讨书
2015/01/26 职场文书
2015年第31个教师节致辞
2015/07/31 职场文书
我爱我班主题班会
2015/08/13 职场文书
用基于python的appium爬取b站直播消费记录
2021/04/17 Python
详解Apache SkyWalking 告警配置指南
2021/04/22 Servers