简体   繁体   中英

VirtualEnv Python as Java PythonInterpreter in MacOS

I'm currently finding a way to get some output from a python script through Java. After finding jython, I used PythonInterpreter to send parameters and receive output I expect.

My Code

    PythonInterpreter interpreter = new PythonInterpreter();
    String fileUrlPath = "/Users/me/Desktop/";
    String scriptName = "pythonScript";
    interpreter.exec("import sys\n" + "import os \n" + "sys.path.append('" + fileUrlPath + "')\n"+ "from "+scriptName+" import * \n");
    String funcName = "predictionFunction";
    PyObject someFunc = interpreter.get(funcName);

    try 
    {
        PyObject out = someFunc.__call__(new PyString(pathToImageFolder), new PyString(fileName));
        System.out.println(out);
    } 
    catch (PyException e) 
    {
        e.printStackTrace();
    }

My Problem

But whenever I launch my program, It shows, numpy module not found error. So I checked the python version and it showed 2.7.0 which is version of jython python interpreter.

But all my python libraries has been installed in a Virtual environment in path path/to/vir/env/bin . So I need to change the interpreter of java PythonInterpreter function to the python I've installed in my virtual environment.

is it possible? If so, really appreciate if someone can help.

What you're asking for is impossible.

Jython can't use C-API extensions, which includes NumPy. Changing the sys.path to include the location where you installed NumPy won't help.

Jython can use Java packages, and there are Java packages for array-based numerics, but none of them is anywhere near a drop-in replacement for NumPy; you'd have to rewrite all of your code to use a pretty different API, and it may not have features you're relying on.


However, if all you're trying to do is call some Python code with some simple string arguments and get back a string as output, you can do that just by running CPython as a subprocess. And it seems like that's exactly what you're doing: you've got some wrapper code that just imports your module, calls a function with two strings, and prints out the return value as a string.

Step 1: Wrap that Python code up in a script that takes its arguments via sys.argv , and outputs its results via print .

Step 2: Run your script with the normal CPython interpreter from the virtualenv that has NumPy installed, and capture its output with a pipe.

Step 3: There is no step 3. (Or was it something something life finds a chaos theory because Earth girls are easy? I don't know, it's all Jeff Goldblum.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM