从python编译java

2024-03-29 00:59:51 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在编写一个脚本,从python中编译一个.java文件 但是这个错误

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

compile_java("Test.java")

错误:

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

我知道如何解决windows上的CMD问题。但是我如何为python解决这个问题呢? 我的意思是:我该如何设置路径?


Tags: 文件import脚本cmdwindowsdef错误proc
2条回答
proc = subprocess.Popen(cmd, shell=True, env = {'PATH': '/path/to/javac'})

或者

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

您还可以发送参数:

            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

接收这些变量的Java代码如下所示:

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

相关问题 更多 >