我正在使用Jyton/ScriptEngine在我的Java应用程序中运行Python脚本,但它不起作用。ScriptEngine找不到JythonScriptEngine。
public static void main(String[] Args) throws FileNotFoundException, ScriptException {
PySystemState engineSys = new PySystemState();
engineSys.path.append(Py.newString("C:/Users/User/AppData/Local/jython2.7.2/jython.jar"));
Py.setSystemState(engineSys);
StringWriter writer = new StringWriter();
ScriptContext context = new SimpleScriptContext();
context.setWriter(writer);
ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = manager.getEngineByName("python");
engine.eval(new FileReader("C:/*/MyScript.py"), context);
System.out.println(engine.get("value"));}
我将Jython添加到我的Libary项目中。
但它不起作用。
我希望有人能帮我。提前谢谢你。:D
发布于 2022-08-30 10:48:51
我没有使用Jython库,但它似乎有助于在java代码中获得python库/解释器。您的代码看起来像是要执行一些python类并在Java中获得结果。您只需将其作为shell命令执行,并获得其结果,如下实用程序函数所示:
public static String runSystemCommand(String fileToRun) throws IOException
{
Process p = Runtime.getRuntime().exec(fileToRun);
BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()));
String result = input.lines().collect(Collectors.joining("\n"));
input.close();
return result;
}
public static void main(String[] args) throws Exception
{
System.out.println(runSystemCommand("python /home/saad/shell.py"));
}
发布于 2022-08-30 17:05:51
我找到了一个使用ProcessBuilder的解决方案。它在shell中运行我的python脚本,就像@saadeez向我展示的那样。
@Test
public void givenPythonScript_whenPythonProcessInvoked_thenSuccess() throws Exception {
ProcessBuilder processBuilder = new ProcessBuilder("python", "C:.py");
processBuilder.redirectErrorStream(true);
Process process = processBuilder.start();
List<String> results = readProcessOutput(process.getInputStream());
System.out.println(results);
int exitCode = process.waitFor();
assertEquals("0", ""+exitCode);}
public static String runSystemCommand(String fileToRun) throws IOException
{
Process p = Runtime.getRuntime().exec(fileToRun);
BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()));
String result = input.lines().collect(Collectors.joining("\n"));
input.close();
return result;}
https://stackoverflow.com/questions/73540502
复制相似问题