在python中编译和执行Java文件

时间:2013-10-20 15:46:27

标签: python python-3.x

如何在python中打开java文件?我在网上搜索并找到了这个:

import os.path, subprocess
from subprocess import STDOUT, PIPE

def compile_java (java_file):
    subprocess.check_call(['javac', java_file])

def execute_java (java_file):
    cmd=['java', java_file]
    proc=subprocess.Popen(cmd, stdout = PIPE, stderr = STDOUT)
    input = subprocess.Popen(cmd, stdin = PIPE)
    print(proc.stdout.read())

compile_java("CsMain.java")
execute_java("CsMain")

然后我收到了这个错误:

Traceback (most recent call last):
  File "C:\Python33\lib\subprocess.py", line 1106, in _execute_child
    startupinfo)
FileNotFoundError: [WinError 2] The system cannot find the file specified

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\casestudy\opener.py", line 13, in <module>
    compile_java("CsMain.java")
  File "C:\casestudy\opener.py", line 5, in compile_java
    subprocess.check_call(['javac', java_file])
  File "C:\Python33\lib\subprocess.py", line 539, in check_call
    retcode = call(*popenargs, **kwargs)
  File "C:\Python33\lib\subprocess.py", line 520, in call
    with Popen(*popenargs, **kwargs) as p:
  File "C:\Python33\lib\subprocess.py", line 820, in __init__
    restore_signals, start_new_session)
  File "C:\Python33\lib\subprocess.py", line 1112, in _execute_child
    raise WindowsError(*e.args)
FileNotFoundError: [WinError 2] The system cannot find the file specified
>>> 

python文件和java文件在同一个文件夹中,我使用的是Python 3.3.2,如何解决这个问题?或者你们有另外一种做法吗?任何答案都表示赞赏谢谢!

2 个答案:

答案 0 :(得分:1)

我认为它没有识别javac命令。尝试手动运行该命令,如果javac不是可识别的命令,请在PATH变量中注册,然后重试。

或者您可以尝试键入javacjava的Java目录的完整路径名。

答案 1 :(得分:0)

您需要将path添加到您的java文件名中。像这样:

compile_java("C:\\path\to\this\CsMain.java")