ninia / jep

Embed Python in Java
Other
1.31k stars 149 forks source link

Call runScript() method with parameter #535

Closed noobshmily closed 4 months ago

noobshmily commented 4 months ago

Describe the problem I have a python file with a lot of code, so I want to use runScript() to invoke this file, but i don't know how to pass the parameter.

Environment (please complete the following information):

noobshmily commented 4 months ago

I figure out how to pass the patemeter with runScript(), here is an example


class JepTest {

    private static Interpreter interpreter;

    @BeforeAll
    static void before() {
        interpreter = new SharedInterpreter();
    }

    @AfterAll
    static void afterAll() {
        interpreter.close();
    }

    @Test
    void test() {
        String pythonSourcePath = "path/to/your/python/file";

        // Use Spring path util
        ClassPathResource classPathResource = new ClassPathResource(pythonSourcePath);

        Map<String, Object> kwargs = new HashMap<>();

        // Put the parameter into the kwargs 
        kwargs.put("param_key", "param_value")

        interpreter.runScript(classPathResource.getPath());
        Object solveResult = interpreter.invoke("method_name", kwargs);

        // Find the most suitable type to receive the result
        NDArray<double[]> result = (NDArray<double[]>) solveResult;
        System.out.println(Arrays.toString(result.getData()));
        Assertions.assertTrue(true);
    }
}