Several ways to run Python scripts in Java
1. Use Jython
Jython is a Python interpreter implemented entirely in Java, which allows running Python code on a Java virtual machine (JVM). With Jython, you can call Python code directly in a Java program and vice versa.
import ; public class RunPythonWithJython { public static void main(String[] args) { PythonInterpreter interpreter = new PythonInterpreter(); ("print('Hello, World from Jython!')"); } }
2. Use Jep
Jep (Java Embed Python) is a Python embed and interpreted library that provides an interface to call Python code in a Java program. Jep supports extension modules written by CPython and can handle Python exceptions.
import com.; public class RunPythonWithJep { public static void main(String[] args) { (); ("print('Hello, World from Jep!')"); (); } }
3. Use ScriptEngineManager
The ScriptEngineManager class in Java can be used to manage a variety of scripting engines, including the JSR-223-compatible Python engine. This approach requires a JSR-223-compatible Python scripting engine, such as ScriptEngine in the package.
import ; import ; public class RunPythonWithScriptEngine { public static void main(String[] args) { ScriptEngineManager manager = new ScriptEngineManager(); ScriptEngine engine = ("python"); ("print('Hello, World from ScriptEngine!')"); } }
4. Use ProcessBuilder
If you just want to run a Python script file instead of executing Python code directly in a Java program, you can use ProcessBuilder
to start an external process.
import ; import ; import ; public class RunPythonScriptWithProcessBuilder { public static void main(String[] args) { List<String> command = ("python", ""); ProcessBuilder builder = new ProcessBuilder(command); try { Process process = (); BufferedReader reader = new BufferedReader(new InputStreamReader(())); String line; while ((line = ()) != null) { (line); } } catch (Exception e) { (); } } }
The above are several ways to run Python scripts in Java. Each method has its own characteristics and applicable scenarios. Which method to choose depends on your specific needs and preferences. For example, if you need deep integration of Python and Java, Jython or Jep may be a better choice; if you just want to run a standalone Python script, using ProcessBuilder may be easier. Running Python scripts in Java usually involves using Jython because Jython provides the ability to run Python code on a Java virtual machine (JVM). Jython allows you to call Python code directly from Java and vice versa. Here are some example codes for running Python scripts in Java:
1. Use ScriptEngineManager and ScriptEngine
Java's
Package providedScriptEngineManager
andScriptEngine
Classes, they can be used to execute scripting languages, including Jython.
import ; import ; import ; public class RunPythonScript { public static void main(String[] args) { try { // Get the ScriptEngineManager instance ScriptEngineManager scriptEngineManager = new ScriptEngineManager(); // Get Jython ScriptEngine ScriptEngine jython = ("python"); // Execute Python scripts ("print('Hello, World!')"); } catch (ScriptException e) { (); } } }
2. Use ProcessBuilder
You can also useProcessBuilder
To run Python scripts, this way allows you to execute any system commands in Java, including Python scripts.
import ; import ; import ; import ; public class RunPythonScript { public static void main(String[] args) { try { // Set the path to the Python script String scriptPath = "path/to/your/python_script.py"; // Create ProcessBuilder object List<String> command = ("python", scriptPath); ProcessBuilder processBuilder = new ProcessBuilder(command); // Starter child process Process process = (); // Read the output BufferedReader reader = new BufferedReader(new InputStreamReader(())); String line; while ((line = ()) != null) { (line); } } catch (IOException e) { (); } } }
3. Use ().exec()
This is another useRuntime
Methods to execute external commands, including Python scripts.
import ; import ; import ; public class RunPythonScript { public static void main(String[] args) { try { // Set the path to the Python script String scriptPath = "path/to/your/python_script.py"; // Create Process object Process process = ().exec("python " + scriptPath); // Read the output BufferedReader reader = new BufferedReader(new InputStreamReader(())); String line; while ((line = ()) != null) { (line); } } catch (IOException e) { (); } } }
4. Use jpy
jpy
is a lightweight library that provides a simple interface for calling Python scripts in Java.
import ; import ; import ; public class RunPythonScript { public static void main(String[] args) { try { // Initialize JPy PyObject jpy = new PyObject("jpy"); // Call Python script PyObject result = ("your_python_script.py"); // Process the return value (()); } catch (PyException e) { (); } } }
Please note that in the above code examplepath/to/your/python_script.py
Requires replacement with your actual Python script path. Also, make sure your Java project has the appropriate permissions to execute system commands or access the Jython library. There are three main ways to run Python scripts in Java:
- Using Jython Jython is a Python interpreter that runs on a Java virtual machine (JVM). This means you can run Python code directly in a Java environment. To use Jython, you need to first add Jython's JAR file to your Java project and then use the Python Interpreter class to execute Python scripts.
Here is a simple Java code example that uses Jython to execute a Python script:
import ; public class RunPythonScript { public static void main(String[] args) { PythonInterpreter interpreter = new PythonInterpreter(); ("your_python_script.py"); // Replace with the actual Python script file path // Or use strings to execute code // ("print('Hello, World!')"); ("Python script executed successfully."); } }
-
Using ScriptEngineManagerJava's
ScriptEngineManager
Classes allow you to use different script engines to execute code for various scripts, including Python. You need to add a Python-enabled scripting engine (such as Jython) to your Java project and then useScriptEngineManager
Come to get oneScriptEngine
Object, and execute Python code through it.
Here is a useScriptEngineManager
Example:
import ; import ; import ; public class RunPythonScript { public static void main(String[] args) { ScriptEngineManager manager = new ScriptEngineManager(); ScriptEngine engine = ("python"); try { ("print('Hello, World!')"); // Or use file path ("Python script executed successfully."); } catch (ScriptException e) { (); } } }
-
Using third-party librariesIn addition to Jython, there are some other third-party libraries that can help you run Python scripts in Java, e.g.
groovy-python
. These libraries usually provide a higher level of abstraction, making it easier to use Python in Java.
usegroovy-python
Example:
import ; public class RunPythonScript { public static void main(String[] args) { GroovyShell shell = new GroovyShell(); ("import sys; print('Hello, World!', file=)"); // Use Groovy to execute Python code ("Python script executed successfully."); } }
Please note that the above code example you have installed and configured the corresponding library (such as Jython orgroovy-python
) and your Java project is able to reference these libraries correctly. When using it, make sure you have installed and configured the required dependencies.
The above is the detailed content of several ways to run Python scripts in Java. For more information about running Python scripts in Java, please pay attention to my other related articles!