python编写脚本替换 jar包文件_你如何使用python在jar文件中调用python脚本?

I'm working on an application that intersperses a bunch of jython and java code. Due to the nature of the program (using wsadmin) we are really restricted to Python 2.1

We currently have a jar containing both java source and .py modules. The code is currently invoked using java, but I'd like to remove this in favor of migrating as much functionality as possible to jython.

The problem I have is that I want to either import or execute python modules inside the existing jar file from a calling jython script. I've tried a couple of different ways without success.

My directory structure looks like:

application.jar

|-- com

|--example

|-- action

|-- MyAction.class

|-- pre_myAction.py

The 1st approach I tried was to do imports from the jar. I added the jar to my sys.path and tried to import the module using both import com.example.action.myAction and import myAction. No success however, even when I put init.py files into the directory at each level.

The 2nd approach I tried was to load the resource using the java class. So I wrote the below code:

import sys

import os

import com.example.action.MyAction as MyAction

scriptName = str(MyAction.getResource('/com/example/action/myAction.py'))

scriptStr = MyAction.getResourceAsStream('/com/example/action/myAction.py')

try:

print execfile(scriptStr)

except:

print "failed 1"

try:

print execfile(scriptName)

except:

print "failed 2"

Both of these failed. I'm at a bit of a loss now as to how I should proceed. Any ideas ?

cheers,

Trevor

解决方案

the following works for me :

import sys

import os

import java.lang.ClassLoader

import java.io.InputStreamReader

import java.io.BufferedReader

loader = java.lang.ClassLoader.getSystemClassLoader()

stream = loader.getResourceAsStream("com/example/action/myAction.py")

reader = java.io.BufferedReader(java.io.InputStreamReader(stream))

script = ""

line = reader.readLine()

while (line != None) :

script += line + "\n"

line = reader.readLine()

exec(script)

Loading the Script from the ClassPath as a String in 'script'

exec the script with exec

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值