将python函数从python3传递给jython 2.2

时间:2017-06-28 04:59:13

标签: python command-line-arguments python-3.4 jython jython-2.2

我有一个python 3代码,它在内部启动一个jython进程,如下所示:

from multiprocessing import Process
import subprocess

def startJython(arg1, arg2, arg3):
    jythonProc = Process(target=initJython, args=(arg1,arg2,arg3,))
    jythonProc.start()

def initJython(arg1,arg2,arg3):
    command = 'java -jar /pathTo/jython.jar /pathTo/myJython.py '+arg1+' '+arg2+' '+arg3
    subprocess.call(command,shell=True)

当参数是字符串时,这很好用。 但是,python允许我们将函数作为参数传递。

如何在此方案中将函数作为参数发送?

我知道它不能通过shell命令完成,因此我也在寻找这个过程的替代方法。

请注意我无法单独在jython或python3中运行整个过程,因为python3使用的是jython 2.2无法导入的导入,反之亦然。

我考虑过使用__name__对象将函数名称作为字符串传递,但是我的jython代码可能无法导入该函数,因为它不知道从哪里导入它。< /强>

最佳解决方案是什么?感谢

2 个答案:

答案 0 :(得分:1)

当然答案是将您的函数写入文件,然后将文件名作为参数传递给Jython?应该可以编写同时有效的python3代码以及有效的jython,然后可以从这两个地方导入。

答案 1 :(得分:0)

我通过传递以下参数来解决这个问题:

  

arg1 - the name of the function I want to call

     

arg2 - the name of the module that contains the method

     

arg3 - the absolute path to the module

我按照我的问题定义了startJython函数。

在目标myJython.py中,我从arg1,arg2和arg3导入了方法,如下所示:

import sys
testmethod_name = sys.argv[1]
testmethod_module = sys.argv[2]
module_path = sys.argv[3]

sys.path.append(module_path) #append full path to the file to sys.path
testmodule = __import__(testmethod_module) #import the module that contains the method
testmethod = getattr(testmodule, testmethod_name) #type: function