从JAR中执行python文件

我试图找出如何引用python文件,以便我可以在Java GUI Jar中执行它。 它需要是一个可移植的解决方案,所以使用绝对路径对我来说不起作用。 我在下面列出了我的项目结构,并且包含了我如何尝试执行python脚本的代码。我已经阅读了有关使用资源的内容,但我无法成功实现。 我感谢您提供的任何帮助!

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) { try { Runtime rt = Runtime.getRuntime(); Process pr = rt.exec("python /scripts/script.py"); BufferedReader bfr = new BufferedReader(new InputStreamReader(pr.getInputStream())); String line = ""; while((line = bfr.readLine()) != null) System.out.println(line); } catch(Exception e) { System.out.println(e.toString()); } } --OneStopShop (Project) --Source Packages --images --onestopshop --Home.java --scripts --script.py 

使用/启动文件路径意味着您要从文件系统的根目录开始。

只需删除前导斜杠,您的代码就可以为我工作:

 public static void main(String[] args) { try { File python = new File("scripts/script.py"); System.out.println(python.exists()); // true Runtime rt = Runtime.getRuntime(); Process pr = rt.exec("python scripts/script.py"); // print('Hello!') BufferedReader bfr = new BufferedReader(new InputStreamReader(pr.getInputStream())); String line = ""; while((line = bfr.readLine()) != null) System.out.println(line); } catch(Exception e) { System.out.println(e.toString()); } } // true // Hello! // Process finished with exit code 0 

放错文件没有显示错误的原因是因为这个java代码只显示输入流( getInputStream() ),而不是错误流( getErrorStream() ):

  public static void main(String[] args) { try { Runtime rt = Runtime.getRuntime(); Process pr = rt.exec("python scripts/doesnotexist.py"); BufferedReader bfr = new BufferedReader(new InputStreamReader(pr.getErrorStream())); String line = ""; while((line = bfr.readLine()) != null) System.out.println(line); } catch(Exception e) { System.out.println(e.toString()); } } // python: can't open file 'scripts/doesnotexist.py': [Errno 2] No such file or directory // Process finished with exit code 0