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

查看:43
本文介绍了如何使用 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.myActionimport 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 ?

干杯,

特雷弗

推荐答案

以下对我有用:

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 + "
"
    line = reader.readLine()

exec(script)

  1. 从 ClassPath 加载脚本作为 'script' 中的字符串
  2. 用exec执行脚本

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

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