The two ways that Java calls Python
1.Runtime
Private Staticstring Call_python (String input_argv) {string Python_py= "c:/users/lichaoxing/desktop/python_test.py"; String result=NULL; Try{string[] args1=NewString[] {"Python", Python_py, input_argv}; Process proc=runtime.getruntime (). exec (ARGS1); InputStreamReader stdin=NewInputStreamReader (Proc.getinputstream ()); LineNumberReader input=NewLineNumberReader (stdin); Result=Input.readline (); } Catch(IOException e) {e.printstacktrace (); } returnresult; }
2.jython
Public classjython{ Public Static voidMain (string[] args)throwsException {Try{Pythoninterpreter Interpreter=NewPythoninterpreter (); Interpreter.execfile ("C:\\users\\lichaoxing\\desktop\\hello.py"); Pyfunction pyfunction= Interpreter.get ("Hello", pyfunction.class); Pyobject Pyobject=pyfunction.__call__ (); System.out.println (Pyobject); }Catch(Exception e) {e.printstacktrace (); } }}
problems encountered :
- In Jython mode, if Python calls a third-party Python library, it will error (may not be supported, or the workaround is to specify the path of the third-party library, I have not tried)
- And one more question is
It means that there is no permission to create a cache folder for your own use (under Windows environment, if Linux may be a different problem, never tried)
- It's more convenient than using runtime, and it supports Python to import third-party libraries
- Here's a special note that my Python script has read-in files, where the file path is in the same folder as Python, but Java is not in the same path as they do
Cause, run time, no error also have output, finally found the reason is that the Python read the file path Java is not aware of
(It's strange here, obviously just run a Python script with Java, then Python executes, end output in the output buffer, waiting for Java to fetch, but why do you have to let Java know the path of this file)
Workaround :
Experiment, you can specify the absolute path of the file directly in Python
Better way to pass files to Python as parameters in Java
[Java/python] Java calls Python script issue record