关于Java和C#对Python脚本的调用

C#调用Python脚本:

示例:

        private string RunPythonScript(string filePath, string length)
        {
     
            Process p = new Process();
 
            // 编写参数
            string arges = "\""+filePath + "\" " + length;
 
            // python环境,有环境变量直接是python.exe, 如果没有环境变量则为python.exe的绝对路径
            p.StartInfo.FileName = @"python.exe";
            // p.StartInfo.FileName = @"E:\workArea\PycharmProjects\Demo\venv\Scripts\python.exe";
            // python脚本路径
            p.StartInfo.Arguments = "\""+AppDomain.CurrentDomain.BaseDirectory + "custom/lib/Script/SteadyStateRotationTest.py"+"\" " + arges;
            p.StartInfo.UseShellExecute = false;
            p.StartInfo.RedirectStandardOutput = true;
            p.Start();
            // p.BeginOutputReadLine();
            StreamReader reader = p.StandardOutput;
            string result = "";
            while (!reader.EndOfStream)
            {
     
                result = reader.ReadLine();
            }
            p.WaitForExit();
            return result;
        }

Java调用Python脚本:

示例:

public class PythonScriptRunner {
     

    private static final String PYTHON = "python";

    public static JSONObject run(String scriptPath, String args) {
     
        JSONObject result = new JSONObject();
        String[] arguments = new String[]{
     PYTHON, scriptPath, args};
        try {
     
            Process process = Runtime.getRuntime().exec(arguments);
            BufferedReader in = new BufferedReader(new InputStreamReader(process.getInputStream(), "GBK"));
            String line = in.readLine();
//            while ((line = in.readLine()) != null) {
     
//                System.out.println(line);
//            }
            in.close();
            //java代码中的process.waitFor()返回值为0表示我们调用python脚本成功,
            //返回值为1表示调用python脚本失败,这和我们通常意义上见到的0与1定义正好相反
            int re = process.waitFor();
            if (re == 1) {
     
                result.put("success", false);
                result.put("msg", "脚本调用失败,原因:" + line);
            } else {
     
                result.put("success", true);
                result.put("data", line);
            }
        } catch (Exception e) {
     
            e.printStackTrace();
            result.put("success", false);
            result.put("msg", e.getMessage());
        }
        return result;
    }
}

你可能感兴趣的:(Java,C#,python,java,c#)