You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过Java代码运行.py脚本?Python新手寻求帮助

Java调用Python脚本(基于Jython)

Hey there! I totally get your frustration—most Jython tutorials focus on Python calling Java, but we can absolutely do the reverse. Since you're new to Python, let's keep this straightforward and practical.

核心思路

Jython provides a PythonInterpreter class that lets Java load and execute Python code directly. You just need to make sure the Jython standalone JAR is added to your Java project's classpath (no fancy setup beyond that!).

两种常见实现方式

1. 直接运行Python代码片段

If you want to run short Python snippets right inside your Java program, use this simple approach:

import org.python.util.PythonInterpreter;

public class JavaRunPythonSnippet {
    public static void main(String[] args) {
        // Use try-with-resources to auto-close the interpreter (cleaner code!)
        try (PythonInterpreter pyInterp = new PythonInterpreter()) {
            // Execute a single Python line
            pyInterp.exec("print('Hi from Python, called by Java!')");
            
            // Execute multi-line Python code with triple quotes
            pyInterp.exec("""
                num1 = 12
                num2 = 4
                print(f"Division result: {num1 / num2}")
                """);
        }
    }
}

2. 加载外部.py脚本文件

If you have a separate Python script (e.g., my_script.py), here's how to call it and even invoke its functions:

First, your my_script.py file:

# my_script.py
def greet_user(name):
    return f"Hello {name}! Nice to meet you from Python."

print("External Python script is up and running!")

Then the corresponding Java code:

import org.python.util.PythonInterpreter;
import org.python.core.PyObject;

public class JavaCallExternalPyScript {
    public static void main(String[] args) {
        try (PythonInterpreter pyInterp = new PythonInterpreter()) {
            // Load and execute the external script
            pyInterp.execfile("my_script.py");
            
            // Grab the Python function from the interpreter
            PyObject greetFunc = pyInterp.get("greet_user");
            
            // Call the function with a parameter and fetch the result
            PyObject greetResult = greetFunc.__call__(PythonInterpreter.get("Anisha"));
            System.out.println("Python function returned: " + greetResult.toString());
        }
    }
}

关键注意事项

  • Classpath Setup: Make sure you've added the Jython standalone JAR (like jython-standalone-2.7.3.jar) to your Java project. If you're using an IDE, just import the JAR as a library.
  • Third-Party Libraries: Jython doesn't support all CPython libraries (e.g., pandas or numpy might not work). If your script relies on these, you'll need to use Java's ProcessBuilder to call your system's native Python interpreter instead.
  • Error Handling: Add try-catch blocks around the interpreter code to handle issues like missing scripts or Python syntax errors—this will make your code more robust.

内容的提问来源于stack exchange,提问作者Anisha

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 11:55:10