I have a Java Swing class from which I want my Java application to run a local python program after clicking a button. The following code does not run the executable python I have created.
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);
}
}
I have even tried running the python script file using:
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);
}
}
I have no errors yet neither does the job. I can run applications like notepad etc using the same syntax, however I cant with python and I'm unsure how to resolve this. Ps I do have Python 2.7 PATH in my environment variable. Also, the above are just the methods for the action performed by the buttons. I have all the other methods and main class in my full program.
Process p= Runtime.getRuntime().exec("cmd /c /K \"C:\\Python27\\python.exe C:\\Users\\User\\Desktop\\hello.py\"");
do this way.. call the Python from cmd
I tried this simple example & it worked for me... Files : CallPython.java
& hello.py
CallPython.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...");
}
}
}
hello.py
print('Hello...from python script');
Output:
Hello...from python script
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.