3
votes

I have several python scripts (eg a.py,b.py) that share the same overhead at the top, eg:

import matplotlib.pylab as plt
#and some Oracle database connection and reading.

Then I have a java script that users Runtime to calls these several python scripts separately:

Process p = Runtime.getRuntime().exec("python a.py");
p.waitFor();
...
p = Runtime.getRuntime().exec("python b.py");
p.waitFor();

I suffer from the repeated overhead due to the java Runtime and python import overhead during each python call. I am wondering whether there is a way that involves only one time overhead during the first python call (by passing around some python handler/state maybe?) I am open to third party tools (eg Jython) as well.

3

3 Answers

3
votes

Not sure if this will speed up your program, but one option would be to use Jython to start up a Python interpreter once, and then re-use it for multiple scripts. You just need to add a dependency on the Jython JAR (download it at http://www.jython.org/downloads.html or use Maven/Gradle/etc.)

import org.python.util.PythonInterpreter;
public class JythonTest {
    public static void main(String[] args) {
        PythonInterpreter pythonInterpreter = new PythonInterpreter();
        pythonInterpreter.execfile("a.py");
        pythonInterpreter.execfile("b.py");
    }
}

Ref: http://tssblog.blogs.techtarget.com/2007/11/21/using-python-within-java/

2
votes

Rather than launching each program separately and running to completion, create a "launcher" that reads from standard input, and interact with that launcher - this should be a program that won't exit until it's told to; its entire purpose is to launch other functions.

Then treat it as a resource and use it to call the individual functions and return results (rather than Java's Process).

The same strategy can be used for many different types of external programs that have shared dependencies - the launcher can load the common dependencies/ it's own runtime once, and more quickly call functions in those dependencies.

1
votes

You could launch the Python script once and then communicate repeated tasks with it via some kinda of IPC (inter-process communication). Some ways that come to mind:

  • Access via an HTTP API hosted by the Python process (Java process as the client)
  • If using OS X/Linux use signals
  • Something as simple as delivering instructions via a file - although you would probably need to implement file-locking (so the reader doesn't read an incomplete file if the writer hasn't finished)

However, implementing anyone of these does feels a bit like premature-optimization. Why not first implement the easiest way (as in your example), and profile your CPU usage. Chances are, your current approach won't make as much of a dent in your CPU usage as you might suspect.