How to execute Java Program using Python ?

Executing the java program using Python/Go is much easier than executing the java program in another java program.

Demo:

Visit util.codes wesbite for the live demo.

Executing Java Program using Python:

Here is the core logic to execute the java program using python: (app.py)

from subprocess import Popen, PIPE
import os, errno, subprocess

filename = 'UtilCodes.java'
try:
	os.remove('UtilCodes.java')
except OSError as e:
	print(e)
	pass
f = open("UtilCodes.java", "a")
f.write("import java.time.*;\npublic class UtilCodes {\n\tpublic static void main(String[] args){\n\t\tSystem.out.println( getTodayISTDate() );\n\t}\n\tpublic static LocalDateTime getTodayISTDate() {\n\t\tLocalDateTime localNow = LocalDateTime.now();   \n\t\tZonedDateTime zonedUTC = localNow.atZone(ZoneId.of(\"UTC\"));\n\t\tZonedDateTime zonedIST = zonedUTC.withZoneSameInstant(ZoneId.of(\"Asia/Kolkata\"));\n\t\treturn localNow.now(ZoneId.from(zonedIST));\n\t}\n}")
f.close()
p = Popen('sudo javac UtilCodes.java',stdout=PIPE, stderr=PIPE, shell=True)
output, error = p.communicate()
if p.returncode != 0:
	return error
output = subprocess.check_output("sudo java UtilCodes", stderr=subprocess.PIPE, shell=True)
	return output.decode("utf-8")  
python3.8 app.py // you get the output as the current timestamp as per the above java code

Python Flask RESTAPI to execute Java Program using Python:

REST API Endpoing with python flask to execute the above core logic through the cusom REST API, here request_data contains java source code in the program key.

from flask import Flask, render_template, request, jsonify, redirect, url_for
from pymongo import MongoClient
from bson.json_util import dumps
from subprocess import Popen, PIPE
import os, errno, subprocess
@app.route('/execute', methods=['POST'])
@cross_origin()
def execute():
        request_data = request.get_json()
        filename = 'UtilCodes.java'
        try:
                os.remove('UtilCodes.java')
        except OSError as e:
                print(e)
                pass
        f = open("UtilCodes.java", "a")
        f.write(request_data['program'])
        f.close()
        p = Popen('sudo javac UtilCodes.java',stdout=PIPE, stderr=PIPE, shell=True)
        output, error = p.communicate()
        if p.returncode != 0:
                return error
        output = subprocess.check_output("sudo java UtilCodes", stderr=subprocess.PIPE, shell=True)
        return output.decode("utf-8")

Sample Request:

{
"program":"import java.time.*;\npublic class UtilCodes {\n\tpublic static void main(String[] args){\n\t\tSystem.out.println( getTodayISTDate() );\n\t}\n\tpublic static LocalDateTime getTodayISTDate() {\n\t\tLocalDateTime localNow = LocalDateTime.now();   \n\t\tZonedDateTime zonedUTC = localNow.atZone(ZoneId.of(\"UTC\"));\n\t\tZonedDateTime zonedIST = zonedUTC.withZoneSameInstant(ZoneId.of(\"Asia/Kolkata\"));\n\t\treturn localNow.now(ZoneId.from(zonedIST));\n\t}\n}"
}

Output returns the java compilation error if any or the current timestamp.

Leave a Reply