5

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?

3
  • 3
    Are you sure javac is actually on your Windows PATH? That's likely what it's using Commented Aug 10, 2011 at 19:02
  • Instead of setting the PATH, why not simply provide the absolute path of javac (or javac.exe in your case)? Commented Aug 10, 2011 at 19:18
  • You can try os.environ['PATH'] = PathToJava and see if that works. It works on Linux but I've never tried on Windows. Commented Aug 10, 2011 at 19:23

2 Answers 2

10
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)
Sign up to request clarification or add additional context in comments.

2 Comments

you really don't need shell=True, just pass the arguments as a list
@Jean-FrançoisFabre He may need that for other env setup we don't know about; it was in the question so I left it in the answer.
1

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];

1 Comment

Welcome to Stack Overflow! Could you change your example so it applies to the problem at hand, i.e. invoking javac Test.java instead of java -jar lib/JavaMail.jar?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.