java - 如何从我的 Java 运行 python 2.7 代码?
问题描述
我有一个 Java Swing 类,我希望我的 Java 应用程序在单击按钮后运行本地 python 程序。以下代码不运行我创建的可执行 python。
private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {
try {
// TODO add your handling code here:
Process process =
Runtime.getRuntime().exec("C:\\Users\\User\\Desktop\\hello.exe");
} catch (IOException ex) {
Logger.getLogger(NewJFrame.class.getName()).log(Level.SEVERE, null, ex);
}
}
我什至尝试使用以下命令运行 python 脚本文件:
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
try {
Process p= Runtime.getRuntime().exec("C:\\Python27\\python.exe \"C:\\Users\\User\\Desktop\\hello.py\"");
} catch (IOException ex) {
Logger.getLogger(NewJFrame.class.getName()).log(Level.SEVERE, null, ex);
}
}
我没有错误,但这项工作也没有。我可以使用相同的语法运行记事本等应用程序,但是我不能使用 python,我不确定如何解决这个问题。Ps 我的环境变量中确实有 Python 2.7 PATH。此外,以上只是按钮执行的操作的方法。我的完整程序中有所有其他方法和主类。
解决方案
Process p= Runtime.getRuntime().exec("cmd /c /K \"C:\\Python27\\python.exe C:\\Users\\User\\Desktop\\hello.py\"");
这样做..从cmd调用Python
我尝试了这个简单的示例,它对我有用... 文件:CallPython.java
&hello.py
调用Python.java
import java.util.*;
import java.io.*;
class CallPython{
public static void main(String args[]){
try{
Process proc= Runtime.getRuntime().exec("python hello.py");
BufferedReader stdInput = new BufferedReader(new InputStreamReader(proc.getInputStream()));
/*
BufferedReader stdError = new BufferedReader(new InputStreamReader(proc.getErrorStream()));
// read the output from the command
System.out.println("Here is the standard output of the command:\n");
String s = null;
while ((s = stdInput.readLine()) != null) {
System.out.println(s);
}
*/
stdInput.lines().forEach(System.out::println);
}
catch(IOException e){
System.err.println("Error occured while executing an external process...");
}
}
}
你好.py
print('Hello...from python script');
输出:
Hello...from python script
推荐阅读
- svg - 在圆圈内垂直和水平居中文本
- python-3.x - 使用 python3 -c 命令的 bash 别名
- qt - QML,如何在缩放后告诉项目渲染大小
- constraints - 约束满足中“价值更新”的参考或标准化
- android-volley - 为什么凌空没有完全阅读我的网址字符串
- netlogo - 我将如何在某个区域内“定位”补丁?
- jquery - 即使在失败期间也能从 ajax 请求中获得响应?
- sql - SQL Server 中的 SUM 返回错误值
- vb.net - 是否可以在 windows 窗体面板中滑动一行图像?
- php - Google OAuth 2.0 PHP API 身份验证失败:“使用未定义的常量 STDIN”