Sometimes you need to use JAVA to directly call the python script to execute some server monitoring tasks. This article provides an example code for java to directly call a python script:
Import java. io. BufferedReader;
Import java. io. InputStreamReader;
Public class Main {
Public static void main (String [] args ){
Try {
System. out. println ("start ");
Process pr = runtime.getruntime(cmd.exe c ("python test. py ");
BufferedReader in = new BufferedReader (new InputStreamReader (
Pr. getInputStream ()));
String line;
While (line = in. readLine ())! = Null ){
System. out. println (line );
}
In. close ();
Pr. waitFor ();
System. out. println ("end ");
} Catch (Exception e ){
E. printStackTrace ();
}
}
}
If the following error is reported when running in eclipse:
Java. io. IOException: Cannot run program "python": CreateProcess error = 2
Configure Enviroment in the Run Configuration and add the PATH variable. for details, see: