Home > Blockchain >  How do I compile a string containing Python code in Java
How do I compile a string containing Python code in Java

Time:09-22

Is there a way to compile/check for errors in python code(stored in a string) in Java program. A lot of people give Jython as the solution. If Jython, what's the procedure

CodePudding user response:

You could do something similar to this:

Python code:

  import os
from stat import*
import csv

data = []
with open('Example.csv') as f:
    reader = csv.reader(f, delimiter = ',')
    for row in reader:
        data.append(row)

f = open("Clearprint.csv","w")
f.truncate()
f.close()

with open('Clearprint.csv','w',newline='') as fp:
    a = csv.writer(fp,delimiter = ',')
    a.writerows(data)

Java code:

class test1{

    public static void main(String[] args) throws IOException {
        String pythonScriptPath = "your .py file path";
        String[] cmd = new String[2];
        cmd[0] = "your python.exe path";
        cmd[1] = pythonScriptPath;

        Runtime rt = Runtime.getRuntime();
        Process pr = rt.exec(cmd);

        BufferedReader err = new BufferedReader(new InputStreamReader(pr.getErrorStream()));
        String line = "";
        while((line = err.readLine()) != null) {
        System.err.println(line);
       }
    }   
}

CodePudding user response:

I don't have enough rep to comment this, but this question may be what you're looking for Compiling python code using java. A user mentions "Jython" which may be what fits your description.

Just a warning: If you have an internal IDE for people to practice python (I presume) within your Java app, be wary of returned error messages confusing users since python and java aren't identical in their feedback.

  • Related