Java calls Python

Source: Internet
Author: User
Today, I encountered the problem of calling a Python script in Java. I had to worry about it for a long time and encountered various problems. Most of the online searches use jython, but the python script I want to call contains importurllib, which is not a third-party extension Library, it is available under Lib under python installation path, which can be found under python command line. However, if jython is used, there are too few paths in sys. Sample Code: importorg. pytho... today, I encountered the problem of calling a Python script in Java. I had to worry about it for a long time and encountered various problems. Most of the online searches use jython, but the python script I want to call contains import urllib, which is not a third-party extension Library, it is available under Lib under python installation path, which can be found under python command line. However, if jython is used, there are too few paths in sys. Sample code:

import org.python.core.Py;import org.python.core.PySystemState;import org.python.util.PythonInterpreter;public class Test3 {    /**     * @param args     */    public static void main(String[] args) {                PythonInterpreter interpreter = new PythonInterpreter();                  PySystemState sys = Py.getSystemState();         //sys.path.add("D:\\jython2.5.2\\Lib");        System.out.println(sys.path.toString());                 interpreter.exec("print 'hello'");                  interpreter.exec("import sys");        interpreter.exec("print sys.path");        //        interpreter.exec("import urllib");//        interpreter.exec("print urllib");    }}

The printed sys. path is:

Txt code

['D: \ eclipse_jee_workspace \ ZLabTest \ lib \ Lib ',' _ classpath _ ',' _ pyclasspath _/']

Here, only the eclipse Project path is included, so urllib cannot be found. In the command line, print sys. path as follows:


Similar to sys. path. add ("D: \ jython2.5.2 \ Lib"); add one by one, so give up jython.

You can use runtime.getruntime(cmd.exe c ("python test. py"). The sample code is as follows:

import java.io.BufferedReader;import java.io.InputStreamReader;public class Test5 {        public static void main(String[] args){                try{                        System.out.println("start");                        Process pr = Runtime.getRuntime().exec("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();                        }                }}

The content of the test. py file is:

Python code

import sys  import urllib  print "hello"  print sys.path

The result of running the java program is:

Txt code

start  hello  ['D:\\eclipse_jee_workspace\\ZLabTest', 'C:\\Windows\\system32\\python27.zip', 'D:\\Python27\\DLLs', 'D:\\Python27\\lib', 'D:\\Python27\\lib\\plat-win', 'D:\\Python27\\lib\\lib-tk', 'D:\\Python27', 'D:\\Python27\\lib\\site-packages']end


This is correct. However, we still encountered many problems in the middle. running the java program above in Eclipse throws an exception:

Java. io. IOException: Cannot run program "python": CreateProcess error = 2, too many errors» μ too many errors ¶

At java. lang. ProcessBuilder. start (ProcessBuilder. java: 460)

At java.lang.Runtime.exe c (Runtime. java: 593)

At java.lang.Runtime.exe c (Runtime. java: 431)

At java.lang.Runtime.exe c (Runtime. java: 328)

At com. mysrc. Test5.main (Test5.java: 10)

Caused by: java. io. IOException: CreateProcess error = 2, too many errors» μ too many errors ¶

At java. lang. ProcessImpl. create (Native Method)

At java. lang. ProcessImpl. (ProcessImpl. java: 81)

At java. lang. ProcessImpl. start (ProcessImpl. java: 30)

At java. lang. ProcessBuilder. start (ProcessBuilder. java: 453)

... 4 more

It is impossible to call the python program, but if it is compiled with javac in the command line, and then executed in java, it must be correct. How can I run it properly in Eclipse? after checking it online for half a day, create a PATH in run configurations> environment, set the value to the PATH of the python to be installed, and then run it.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.