In Java programs sometimes you need to call Python's program, you can use the general pyfunction to invoke the Python function and get the return value, but in this way there may be some inexplicable errors, such as Importerror. Another way to do this is to use the Java runtime to invoke the Python program just as you would call a Python script on the command line. At this point, you can pass a file as a script parameter to the parameters required by the Python program, and from the input and output stream of the script to get the results that were originally printed on the console.
Prepare a python file first:
defget_path (filename): y_t=np.loadtxt (filename) Peolpex=Int (y_t[0][0]) Peolpey= Int (y_t[0][1]) FireX= Int (y_t[1][0]) firey= Int (y_t[1][1]) Answer=GetQ (Peolpex, Peolpey, FireX, Firey)returnAnswerif __name__=="__main__": FileName= Sys.argv[1] #print (filename) #root = Tk () #canvas = canvas (Root, bg= "white") #Canvas.pack () #colors = [' red ', ' orange ', ' green ', ' black ', ' yellow ', ' white ', ' pink ']result=get_path (filename)#with open (filename, ' W ') as F: #f.write (Result) PrintResult
The corresponding Java program is as follows:
String result = ""; Try{Process Process= Runtime.getruntime (). EXEC ("python/home/jia/fireevacuation/my.py" +filename);//process.waitfor ();InputStreamReader IR =NewInputStreamReader (Process.getinputstream ()); LineNumberReader input=NewLineNumberReader (IR); Result=Input.readline (); Input.close (); Ir.close ();//process.waitfor ();}Catch(IOException e) {logger.error ("An error occurred while invoking the Python script and reading the result:" +e.getmessage ()); } returnResult
Java invokes a Python script and gets the return value