Skip to content

Instantly share code, notes, and snippets.

@n3rada
Last active July 1, 2024 22:07
Show Gist options
  • Save n3rada/0610814a846c379c2148e47c36b4fabe to your computer and use it in GitHub Desktop.
Save n3rada/0610814a846c379c2148e47c36b4fabe to your computer and use it in GitHub Desktop.
Run Java Code From Python3
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)
@n3rada
Copy link
Author

n3rada commented Jun 28, 2024

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment