tgoossens
tgoossens

Reputation: 9856

Compiling java from python

I'm writing a script to compile a .java file from within python But the error

import subprocess
def compile_java(java_file):
    cmd = 'javac ' + java_file 
    proc = subprocess.Popen(cmd, shell=True)

compile_java("Test.java")

Error:

javac is not recognized as an internal or external command windows 7

I know how to fix the problem for CMD on windows. But how do I solve it for python? What I mean is: how do i set the path?

Upvotes: 5

Views: 10929

Answers (2)

3ck
3ck

Reputation: 539

You can also send arguments as well:

            variableNamePython = subprocess.Popen(["java", "-jar", "lib/JavaTest.jar", variable1, variable2, variable3], stdout=subprocess.PIPE)
            JavaVariableReturned = variableNamePython.stdout.read()
            print "The Variable Returned by Java is: " + JavaVariableReturned

The Java code to receive these variables will look like:

public class JavaTest {
    public static void main(String[] args) throws Exception {
        String variable1 = args[0];
        String variable2 = args[1];
        String variable3 = args[2];

Upvotes: 1

agf
agf

Reputation: 176730

proc = subprocess.Popen(cmd, shell=True, env = {'PATH': '/path/to/javac'})

or

cmd = '/path/to/javac/javac ' + java_file 
proc = subprocess.Popen(cmd, shell=True)

Upvotes: 10

Related Questions