通过tomcatservlet在Java中运行python脚本

2024-06-28 19:30:18 发布

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

大家好,我正在我的Raspberrypi上使用一个自编码的tomcat servlet。 Servlet工作得很好,至少到了应该在Raspberry上执行python脚本的程度。在

我的Java代码是这样的:

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class GoogleServlet extends HttpServlet {
    public static int i = 0;
    public static String string = "";
public GoogleServlet() {
}

protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    ServletOutputStream output = resp.getOutputStream();
    output.println("Hello There I am Raspberry DOS");
    ++i;
    output.println("The number is: " + i);
    String outputValue = req.getParameter("value");
    if(outputValue == null) return;
    output.println("Output Value: " + outputValue);


    if (outputValue.equalsIgnoreCase("close light")) {
        String pythonScriptPath = "/var/lib/tomcat8/webapps/ROOT/WEB-INF/classes/light.py";
        String[] cmd = new String[2];
        cmd[0] = "python";
        cmd[1] = pythonScriptPath;

        Runtime rt = Runtime.getRuntime();
        Process pr = rt.exec(cmd);
    }
  }
}   

在运行名为轻.py包含以下内容:

^{pr2}$

当我打电话给网站的时候。http://adress:8080/test?value=close%20light Servlet向我的PC发送“你好,我是Raspberry DOS”和“数字是:1”,但在我的Raspbery上什么也没有发生。在

我确信python scrip wich的权限777没有以正确的方式执行,有没有可能用于执行python文件的java代码是错误的?在


Tags: 代码importcmdhttpoutputstringjavapublic