你如何使用python在jar文件中调用python脚本? [英] How do you invoke a python script inside a jar file using python?

查看:1040
本文介绍了你如何使用python在jar文件中调用python脚本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

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.

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

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.

我的目录结构如下:

application.jar
  |-- com
       |--example
            |-- action
                 |-- MyAction.class
                 |-- pre_myAction.py

我尝试的第一种方法是从jar进行导入。我将jar添加到我的sys.path并尝试使用 import com.example.action.myAction import myAction 导入模块。但是,即使我将 init .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.

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

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 ?

干杯,

Trevor

推荐答案

以下对我有用:

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)




  1. 将脚本从ClassPath作为字符串加载到'script'中

  2. 用exec执行脚本

这篇关于你如何使用python在jar文件中调用python脚本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆