你如何使用python在jar文件中调用python脚本?

Tre*_*vor 7 python java import jython jar

我正在开发一个散布一堆jython和java代码的应用程序.由于程序的性质(使用wsadmin),我们实际上仅限于Python 2.1

我们目前有一个包含java源和.py模块的jar.该代码目前使用java调用,但我想删除它,以支持尽可能多的功能迁移到jython.

我遇到的问题是我想从调用jython脚本导入或执行现有jar文件中的python模块.我尝试了几种不同的方法但没有成功.

我的目录结构如下:

application.jar
  |-- com
       |--example
            |-- action
                 |-- MyAction.class
                 |-- pre_myAction.py
Run Code Online (Sandbox Code Playgroud)

我试过的第一种方法是从罐子里进口.我将jar添加到我的sys.path并尝试使用import com.example.action.myAction 导入模块并导入myAction.但是,即使我将init .py文件放入每个级别的目录中也没有成功.

我尝试的第二种方法是使用java类加载资源.所以我写了下面的代码:

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"
Run Code Online (Sandbox Code Playgroud)

这两个都失败了.关于我该如何继续,我现在有点不知所措.有任何想法吗 ?

干杯,

特雷弗

Bla*_*ohr 5

以下为我工作:

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)
Run Code Online (Sandbox Code Playgroud)
  1. 在"脚本"中将ClassPath中的脚本作为字符串加载
  2. 用exec执行脚本