Last active
July 1, 2024 22:07
-
-
Save n3rada/0610814a846c379c2148e47c36b4fabe to your computer and use it in GitHub Desktop.
Run Java Code From Python3
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import subprocess | |
import tempfile | |
import os | |
def run_java_code(java_code: str, *args) -> str: | |
""" | |
Executes a given Java code string as a standalone Java program. This function writes the code | |
to a temporary file, executes it using Java's direct execution feature (introduced in Java 11), | |
captures the output, and performs cleanup. | |
Args: | |
java_code (str): A string containing the full Java code. This must include a public class | |
definition. The execution entry point should be in this class. | |
*args (tuple): Variable length argument list, where each argument is passed to the | |
Java program as command line arguments. All arguments are converted to strings. | |
Returns: | |
str: The stdout captured from the Java program after successful execution. If compilation | |
or execution fails, returns None and prints an error message to the standard output. | |
Raises: | |
This function does not raise any exceptions directly but will print error messages | |
to standard output in case of compilation or execution errors. | |
""" | |
# Create a temporary file to hold the Java code | |
with tempfile.NamedTemporaryFile( | |
delete=False, suffix=".java", mode="w", encoding="utf-8" | |
) as java_file: | |
java_file.write(java_code) | |
java_filename = java_file.name | |
try: | |
# Prepare the command to run the Java program, converting all arguments to strings | |
run_command = ["java", java_filename] + [str(arg) for arg in args] | |
# Execute the Java program | |
run_result = subprocess.run( | |
run_command, | |
capture_output=True, | |
text=True, | |
check=False, # Handling error checking manually | |
) | |
if run_result.returncode != 0: | |
print(f"[x] Execution failed:\n{run_result.stderr}") | |
return None | |
return run_result.stdout | |
finally: | |
# Clean up: remove the temporary Java file | |
if os.path.exists(java_filename): | |
os.remove(java_filename) | |
# Example Java code that should be correctly named according to its public class | |
java_code = """ | |
public class Temp { | |
public static void main(String[] args) { | |
System.out.println("Hello from Java!"); | |
} | |
} | |
""" | |
# Running the provided Java code | |
if output := run_java_code(java_code): | |
print(output) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Starting with Java 11, you can run a single-file program directly using
java <filename>.java
. This feature simplifies the process for small programs or scripts by implicitly compiling and running the Java code in one step.