我为servlet编写了以下代码:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class Summarize extends HttpServlet {
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
resp.setContentType("text/html");
PrintWriter out = resp.getWriter();
String str = req.getParameter("txt");
try {
//instead of writing just test.py, write the whole path to the python script it will work perfectly
Process p = Runtime.getRuntime().exec("python test.py");
p.waitFor();
BufferedReader in = new BufferedReader(new InputStreamReader(
p.getInputStream()));
StringBuffer buf = new StringBuffer("");
String line = null;
System.out.println(p.toString());
while ((line = in.readLine()) != null) {
System.out.println(line);
buf.append(line);
}
System.out.println(buf.length());
out.println("this is summarize class");
} catch (Exception e) {
e.printStackTrace();
}
}
}
这段代码不会返回任何内容,但如果我在一个简单的java类中编写相同的代码,代码就可以正常工作。
我还检查了python脚本,它运行得很好 有没有什么办法解决这一问题?
更新:
以下代码现在只需在try语句
答案 0 :(得分:2)
我建议使用Jython
Jython是Java中的Python编程语言的实现,在Java虚拟机(JVM)上运行,而不是在C(CPython)中实现的Python的标准实现。 Python开发人员可以使用它来利用Java社区可用的大量库,这意味着在应用程序中添加一些Java集成。
示例here
import org.python.util.PythonInterpreter;
import org.python.core.*;
public class SimpleExample {
public static void main(String[] args) throws PyException
{
PythonInterpreter pi = new PythonInterpreter();
pi.set("integer", new PyInteger(42));
pi.exec("square = integer*integer");
PyInteger square = (PyInteger)pi.get("square");
System.out.println(“square: ” + square.asInt());
}
}