ホームページ  >  記事  >  バックエンド開発  >  Python Java呼び出し

Python Java呼び出し

巴扎黑
巴扎黑オリジナル
2016-12-03 10:37:01984ブラウズ

<dependency>
    <groupId>jython</groupId>
    <artifactId>jython</artifactId>
    <version>2.1</version>
 </dependency>
package com.curiousby.python.demo;
import org.python.core.PyFunction;
import org.python.core.PyInteger;
import org.python.core.PyObject;
import org.python.util.PythonInterpreter;
/**
 * @author baoyou E-mail:curiousby@163.com
 * @version 2016年8月1日 下午1:05:36
 *
 <dependency>
    <groupId>jython</groupId>
    <artifactId>jython</artifactId>
    <version>2.1</version>
 </dependency>
 *
* desc: ... */ public class PythonByJava { public static void main(String[] args) { PythonInterpreter interpreter = new PythonInterpreter(); interpreter.execfile("I:\\cache\\ea-ws\\DemoJava\\conf\\Test1.py"); PyFunction func = (PyFunction)interpreter.get("sum",PyFunction.class); int a = 1, b = 2 ; PyObject pyobj = func.__call__(new PyInteger(a), new PyInteger(b)); System.out.println(pyobj.toString()); } }

 结果:

3

其他两种 调用方法:

a) 直接执行Python脚本代码

PythonInterpreter interpreter = new PythonInterpreter();  
interpreter.exec("days=(&#39;mod&#39;,&#39;Tue&#39;,&#39;Wed&#39;,&#39;Thu&#39;,&#39;Fri&#39;,&#39;Sat&#39;,&#39;Sun&#39;); ");   ///执行python脚本

b)使用Runtime.getRuntime()执行脚本文件

Process proc = Runtime.getRuntime().exec("python  D:\\demo.py");  
proc.waitFor();


声明:
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。