使用SpringMVC在后台线程中运行python脚本

2024-09-29 10:42:20 发布

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

我有一个SpringMVC应用程序,它需要运行一个python脚本,将zip上传到api。我需要将页面呈现给用户,并在后台运行python脚本,以便在用户继续在Spring应用程序中工作的同时,zip得到更新

    Thread t1 = new Thread(new Runnable() {
                @Override
                public void run() {
                    String[] cmd = {
                            "python",
                            "/Users/rasheenruwisha/final-year-proj/build.py",
                            "ARG 1",
                            "ARG 2",
                    };
                    try {
                        Runtime.getRuntime().exec(cmd);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            });
            t1.start();
            return modelAndView;

这是我目前使用的方法,我没有得到任何错误,但脚本没有得到执行,有什么我做错了吗


Tags: 用户脚本cmdapi应用程序newarg页面
2条回答

1.您还可以使用org.python.util.PythonInterpreter

    PythonInterpreter interpreter = new PythonInterpreter();
    try {
     interpreter.execfile("/Users/rasheenruwisha/final-year-proj/build.py","ARG 1,"ARG 
     2");
    } catch (Exception e) {
        e.printStackTrace();
    }

如果您使用Ubuntu,请添加“sh”和“-c”:

 String[] cmd = {
                            "sh",
                            "-c",
                            "python",
                            "/Users/rasheenruwisha/final-year-proj/build.py",
                            "ARG 1",
                            "ARG 2",
                        };
                        try {
                                Runtime.getRuntime().exec(cmd);
                             } catch (IOException e) {
                                e.printStackTrace();
                             }

相关问题 更多 >