java - Executing a python file from within JAR -
i trying figure out how reference python file can execute within java gui jar. needs portable solution, using absolute paths not work me. have listed project structure below, , have included code how trying execute python script..i have read things using resources, have been unable implement successfully. appreciate can provide!
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
starting file path /
means want start @ root of file system.
your code worked me removing leading slash:
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 exit code 0
the reason why putting wrong file did not show error because java code displays input stream (getinputstream()
), not error stream (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 exit code 0
Comments
Post a Comment