Search code examples
pythoncommand-line-argumentspython-3.4jythonjython-2.2

Passing python function from python3 to jython 2.2


I have a python 3 code, which internally starts a jython process, as shown:

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)

This works well when the arguments are strings. However, python allows us to pass functions as arguments.

How can I send a function as an argument in this scenario ?

I understand that it cannot be done via a shell command, hence I'm also looking for alternate approaches to this process.

Please note that I cannot run the whole process in jython or python3 alone, because python3 uses imports that jython 2.2 cannot import, vice versa.

I considered passing the function name as a string using the __name__ object, but then my jython code may not be able to import that function since it won't know where to import it from.

What is the most optimum solution to this ? Thanks


Solution

  • I solved this problem by passing the following as arguments:

    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

    I ran the startJython function, as defined in my question.

    in the target myJython.py, I imported the method from arg1, arg2 and arg3 as shown:

    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