将 python 函数从 python3 传递给 jython 2.2

Passing python function from python3 to jython 2.2

我有一个python3的代码,内部启动了一个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 代码可能无法导入该函数,因为 它不知道在哪里导入它来自.

对此的最佳解决方案是什么?谢谢

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

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

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