如何使用 python 调用 jar 文件中的 python 脚本?
我正在开发一个散布着一堆 jython 和 java 代码的应用程序。由于程序的性质(使用 wsadmin),我们实际上仅限于 Python 2.1
我们目前有一个包含 java 源代码和 .py 模块的 jar。该代码当前使用 java 调用,但我想删除它,以便将尽可能多的功能迁移到 jython。
我遇到的问题是我想从调用 jython 脚本的现有 jar 文件中导入或执行 python 模块。我尝试了几种不同的方法但没有成功。
我的目录结构如下所示:
application.jar
|-- com
|--example
|-- action
|-- MyAction.class
|-- pre_myAction.py
我尝试的第一种方法是从 jar 中导入。我将 jar 添加到我的 sys.path 中,并尝试使用 import com.example.action.myAction 和 import 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"
这两个都失败了。我现在有点不知所措,不知道该如何继续。有什么想法吗?
干杯,
特雷弗
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
以下对我有用:
the following works for me :