我正在嘗試使用 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 添加到我的專案庫中。
但它沒有用。
我希望有人能幫助我。先感謝您。:D
uj5u.com熱心網友回復:
我沒有使用過 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"));
}
uj5u.com熱心網友回復:
我找到了使用 ProcessBuilder 的解決方法。它像@saadeez 向我展示的那樣在shell 中運行我的python 腳本。
@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://www.uj5u.com/caozuo/505780.html
