This article is quoted from http://www.cnblogs.com/liinux/p/5481849.html
In program development, it is sometimes necessary to call the relevant Python script in a Java program, the following records the first steps and possible solutions to the problem.
1. Create a new MAVEN project in Eclipse;
2. Add the following dependency package to the Pom.xml file after the update MAVEN project;
1234567891011 |
<
dependency
>
<
groupId
>org.python</
groupId
>
<
artifactId
>jython</
artifactId
>
<
version
>2.7.0</
version
>
</
dependency
>
<
dependency
>
<
groupId
>org.python</
groupId
>
<
artifactId
>jython-standalone</
artifactId
>
<
version
>2.7.0</
version
>
</
dependency
>
|
3, write the following test code;
1 Import org.python.util.pythoninterpreter;2 3 public class Jpythonscript {4 public static void Main (String args[]) {5 Pythoninterpreter interpreter = new Pythoninterpreter (); 6 interpreter.exec ("days=" (' MoD ', ' Tue ', ' Wed ', ' Thu ') , ' Fri ', ' Sat ', ' Sun '); "); 7 interpreter.exec (" Print days[1]; "); 8 }9}
4. Test:
The following error occurred:
console:failed to install ': java.nio.charset.UnsupportedCharsetException:cp0. Exception in thread "main" importerror:cannot import site module and its dependencies:no module named Sitedetermine if T He following attributes is correct: * sys.path: [' ... python\\jython\\2.7.0\\lib ', ' __classpath__ ', ' __pyclasspath __/'] This attribute might is including the wrong directories, such as from CPython * sys.prefix:***\jython\2.7.0< C3/>this attribute is set by the system property python.home, although it can be often automatically determined by the Location of the Jython jar fileyou can use the-s option or python.import.site=false to not import the site module
5, Problem solving:
The refactoring code is as follows:
Import Java.util.properties;import Org.python.util.pythoninterpreter;public class Jpythonscript {public static void Main (String args[]) { Properties props = new Properties (); Props.put ("Python.home", "Path to the Lib folder"); Props.put ("python.console.encoding", "UTF-8"); Props.put ("Python.security.respectJavaAccessibility", "false"); Props.put ("Python.import.site", "false"); Properties preprops = System.getproperties (); Pythoninterpreter.initialize (Preprops, props, new string[0]); Pythoninterpreter interpreter = new Pythoninterpreter (); Interpreter.exec ("days=" (' MoD ', ' Tue ', ' Wed ', ' Thu ', ' Fri ', ' Sat ', ' Sun ') ; Interpreter.exec ("Print days[1];");} }
6, compile successfully.
7, problem-solving reference:
http://bugs.jython.org/issue2355
Methods for invoking Python scripts in Java programs