我想弄清楚如何引用 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
关于java - 从 JAR 中执行 python 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25369490/