[英]How do I run a python 2.7 code from my Java?
我有一个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,并且不确定如何解决此问题。 附言:我的环境变量中确实有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
... Files: 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...");
}
}
}
你好
print('Hello...from python script');
输出:
Hello...from python script
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.