精华内容
下载资源
问答
  • Java 调用 Python接口

    2020-11-05 16:44:58
    Java部分 import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.Arrays; import java.util.LinkedList; import java.util.List; import java.util.stream.Collectors; public class...

    Java部分

    import java.io.BufferedReader;
    import java.io.InputStreamReader;
    import java.util.Arrays;
    import java.util.LinkedList;
    import java.util.List;
    import java.util.stream.Collectors;
    
    public class MyDemo {
        public static void main(String[] args) {
            try {
                System.out.println("start");
                String trainData = "1";
                String labers = "1";
                String testData = "-150 -92 -86 -97 -78 -68 -78 -150 -150 -81 -88 -90 -150 -150 -150 -150";
                String[] args1=new String[]{"D:\\python\\python27\\python","D:\\work\\workspace\\fingerprintDatabase\\src\\main\\python\\hello.py", trainData,labers,testData};
                Process pr=Runtime.getRuntime().exec(args1);
    
                BufferedReader in = new BufferedReader(new InputStreamReader(pr.getInputStream()));
                String line;
                System.out.println("return:" + in.readLine());
                while ((line = in.readLine()) != null) {
                    System.out.println(line);
                }
                in.close();
                pr.waitFor();
                System.out.println("end");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    
    }
    

    python部分

    
    if __name__ == '__main__':
        testData = sys.argv[3]
        testData = testData.split(";")
        for i in testData:
            i = i.split(" ")
            i = list(map(int, i))
            X = knn(trainData, i, labels, 1)
            print(X)
    
    
    展开全文
  • java调用python接口问题

    2020-07-01 16:02:27
    现有一个python源码XXXX.py 存放在桌面上 现在有一个python代码片段 ``` def detect(imgfile) ``` 返回参数为: ``` return sorted_label, origimg ... 求大神给出java调用接口的代码 谢谢大神们
  • I want to execute a Python script (including Scipy and Numpy) from Java which should be bundled with the tomcat project by eclipse. Calling Python from Java is trivial:Runtime.getRuntime().exec("pytho...

    I want to execute a Python script (including Scipy and Numpy) from Java which should be bundled with the tomcat project by eclipse. Calling Python from Java is trivial:

    Runtime.getRuntime().exec("python ...");

    How can I achieve bundling the script to call it at the corresponding path? Is this even possible?

    解决方案

    I did some thing similar recently , i am able to run it from eclipse.

    i kept both the jars(jython.jar and plyjy.jar) in lib folder of the Eclipse project and copied the required python files to the src folder of the project.

    Then created an Python Object Instance using the following code

    PySystemObjectFactory factory = new PySystemObjectFactory(InterfaceTye, moduleName,ClassName);

    with the help of factory object we can create an object of the specified module and call the methods of that particular module.

    I was able to achieve it only in eciplse, but i am not sure how to bundle the same for the build

    展开全文
  • import requestsimport unittestimport jsonfrom pubulic_way.get_token import getSessionclass testlogin(unittest.TestCase):def test_getIdentify(self):"...调用test_listCollectInfoByCreditId(se...

    import requests

    import unittest

    import json

    from pubulic_way.get_token import getSession

    class testlogin(unittest.TestCase):

    def test_getIdentify(self):

    """调用test_listCollectInfoByCreditId(self)响应数据中的taxid参数"""

    result = self.get_listCollectInfoByCreditId()

    json_result=json.loads(result)

    p1 = json_result["polygons"][0]["ENTERPRISETAXID"]

    data = {"lyname":"COL_WPOLYGON_3206","id":"8f34969c-ea5e-489c-94bc-37e54ad40660","taxid":p1}

    url = "http://10.17.17.31:8080/LandTaxSys/search/getLayerAlianame"

    headers = {"Content-Type": "application/x-www-form-urlencoded; charset=UTF-8"}

    cookies = self.get_cookies()

    r = requests.post(url,data=data,headers=headers,cookies=cookies)

    # print(p1)

    # print(r.status_code)

    # print(r.text)

    # return r.text

    checkpoint = "91320612MA1UYCL59U"

    if r.status_code == 200:

    if checkpoint in r.text:

    print("测试结果:Passed,断言成功。响应状态码:{}。响应数据【json】:{}".format(r.status_code,r.text))

    else:

    print("测试结果:Failed,断言失败。响应状态码:{}。断言内容为:{}。响应数据【json】:{}".format(r.status_code,checkpoint,r.text))

    else:

    print("测试结果:Failed,接口不通。响应状态码:{}。响应数据【json】:{}".format(r.status_code,r.text))

    def get_listCollectInfoByCreditId(self):

    """获取响应数据中的taxid参数"""

    url = "http://10.17.17.31:8080/LandTaxSys/dataEdit/listCollectInfoByCreditId"

    data = {"start":"1","end":"8","targetTaxId":"91320612MA1UYCL59U","nearbyTaxId":"","swjgDm":"23206","userId":"32060100033"}

    headers = {"Content-Type": "application/x-www-form-urlencoded; charset=UTF-8"}

    cookies = self.get_cookies()

    r = requests.post(url,data=data,headers=headers,cookies=cookies)

    return r.text

    def get_cookies(self):

    cookies = getSession()

    return cookies

    if __name__ == "__main__":

    unittest.main()

    展开全文
  • Java 调用 python接口

    万次阅读 2018-03-06 10:55:23
    最近在做项目的时候,需要java 调用 python 接口,在网上找了一些方法,但是总碰到一些问题,索性将网上的方法和自己的理解总结一下,希望对各位博友有所帮助,也请各位大神不吝赐教。 一:创建环境 Python 环境 ...

        不管什么技术,不管什么问题,只要努力就能解决。

        最近在做项目的时候,需要java 调用 python 接口,在网上找了一些方法,但是总碰到一些问题,索性将网上的方法和自己的理解总结一下,希望对各位博友有所帮助,也请各位大神不吝赐教。

    一:创建环境 Python 环境

    
    import org.python.core.PySystemState;
    import org.python.util.PythonInterpreter;
    /**
     * Jython环境,生存python解释器
     * @author webim
     *
     */
    public final class JythonEnvironment
    {
        private static JythonEnvironment INSTANCE = new JythonEnvironment();
    
        /**
         * 私有构造方法
         */
        private JythonEnvironment()
        {
        }
    
        /**
         * 获取单例
         * @return JythonEnvironment
         */
        public static JythonEnvironment getInstance()
        {
            return INSTANCE;
        }
    
        /**
         * 获取python系统状态,可根据需要指定classloader/sys.stdin/sys.stdout等
         * @return PySystemState
         */
        private PySystemState getPySystemState()
        {
            PySystemState.initialize();
            final PySystemState py = new PySystemState();
            py.setClassLoader(getClass().getClassLoader());
            return py;
        }
    
        /**
         * 获取python解释器
         * @return PythonInterpreter
         */
        public PythonInterpreter getPythonInterpreter(){
            PythonInterpreter inter = new PythonInterpreter(null, getPySystemState());
    //        PythonInterpreter inter = new PythonInterpreter();
            return inter;
        }
        
        
    }
    

     

    二:调用 python 的接口

     

    添加 JPython 依赖

            <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>
    因为 python 和 java是两种不同的语言,因此在项目的 controller 、service 和 mapper 中直接出现 Python 的接口,因此
    自己封装  ExecPython   类,
    封装python的接口,目的让 python 接口和java程序分隔开。

     

    import org.python.core.PyFunction;
    import org.python.core.PyObject;
    import org.python.util.PythonInterpreter;
    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;
    import org.springframework.beans.factory.annotation.Value;
    import org.springframework.stereotype.Component;
    import org.springframework.stereotype.Service;
    
    import java.util.Map;
    
    /*enum的这个用法,可以作为变种的安全单例,值得借鉴哦 ^_^ */
    @Service
    @Component
    public class ExecPython {
    
        public static final Logger logger = LoggerFactory.getLogger(Exception.class);
    
        //定义 python 解释器
        private static PythonInterpreter inter;
    
        public ExecPython() {
            this.inter  = JythonEnvironment.getInstance().getPythonInterpreter();
            this.inter.execfile("C:\\test.py");
        }
    
        //设置 python 脚本的路径
        public void setPythonPath (String pythonPath){
            this.inter.execfile(pythonPath);
        }
    
    
    
        public void execute(String scriptFile, Map<String,String> properties)
        {
            logger.info("获取解释器");
            try
            {
    
                PyFunction getNetInfo = (PyFunction) inter.get("getNetInfo", PyFunction.class);
                PyObject netInfo = getNetInfo.__call__();
                System.out.println("anwser = " + netInfo.toString());
            }
            catch (Exception e)
            {
                e.printStackTrace();
                logger.info("Python 脚本文件执行失败");
            }
        }
    
        //获取 Python 字符串
        public String getString(){
    //获取到python 脚本中的接口
            PyFunction func = (PyFunction) inter.get("adder", PyFunction.class);
            PyObject pyobj = func.__call__();
            System.out.println("anwser = " + pyobj.toString());
            return pyobj.toString();
        }
        // 获取当前数组
        public String getArr() {
            PyFunction getArr = (PyFunction) inter.get("getArr", PyFunction.class);
            PyObject pyobjTwo = getArr.__call__();
            pyobjTwo.__len__();
            System.out.println("anwser = " + pyobjTwo.toString()+" len:"+pyobjTwo.__len__());
    
            //将 PyObject 对象转换成 java  对象
            //Object object = pyobjTwo.__tojava__(List.class);
            //List<String> list = (List<String>) object;
    
            //将查询到数据转换成一个 JSON 字符串
            String result = pyobjTwo.toString();
            String JsonStr = "{" + result + "}";
            logger.info(JsonStr);
            logger.info("将查询的结果转换成 JSON 字符串:",JsonStr);
    
            return pyobjTwo.toString();
        }
    }
     

    三: python 脚本

     

    def adder():    
       return "{'name':'leilei','age':'18'}"  
       
    def getArr():
    return ['aaa','bbb']
    
    
    def getNetInfo():
    return [{'DNS':'192.168.12.3','ip':'45.23.16.0'},{'DNS2':'192.168.12.2','ip2':'45.23.16.2'}]

     

    问题:

    2019-12-09 20:11:17.070 ERROR 4620 --- [           main] o.s.boot.SpringApplication               : Application run failed
    
    org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'execPython' defined in file [D:\Lenovo\LenovoWorkspace\code\ip-modify\target\classes\cn\lenovo\ipmodify\service\ExecPython.class]: Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [cn.lenovo.ipmodify.service.ExecPython]: Constructor threw exception; nested exception is ImportError: Cannot import site module and its dependencies: No module named site
    Determine if the following attributes are correct:
      * sys.path: ['C:\\Users\\31307\\.m2\\repository\\org\\python\\jython\\2.7.0\\Lib', '__classpath__', '__pyclasspath__/']
        This attribute might be including the wrong directories, such as from CPython
      * sys.prefix: C:\Users\31307\.m2\repository\org\python\jython\2.7.0
        This attribute is set by the system property python.home, although it can
        be often automatically determined by the location of the Jython jar file
    
    You can use the -S option or python.import.site=false to not import the site module
    
    	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateBean(AbstractAutowireCapableBeanFactory.java:1320) ~[spring-beans-5.2.2.RELEASE.jar:5.2.2.RELEASE]
    	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1214) ~[spring-beans-5.2.2.RELEASE.jar:5.2.2.RELEASE]
    	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:557) ~[spring-beans-5.2.2.RELEASE.jar:5.2.2.RELEASE]
    	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:517) ~[spring-beans-5.2.2.RELEASE.jar:5.2.2.RELEASE]
    	at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:323) ~[spring-beans-5.2.2.RELEASE.jar:5.2.2.RELEASE]
    	at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222) ~[spring-beans-5.2.2.RELEASE.jar:5.2.2.RELEASE]
    	at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:321) ~[spring-beans-5.2.2.RELEASE.jar:5.2.2.RELEASE]
    	at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:202) ~[spring-beans-5.2.2.RELEASE.jar:5.2.2.RELEASE]
    	at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:879) ~[spring-beans-5.2.2.RELEASE.jar:5.2.2.RELEASE]
    	at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:878) ~[spring-context-5.2.2.RELEASE.jar:5.2.2.RELEASE]
    	at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:550) ~[spring-context-5.2.2.RELEASE.jar:5.2.2.RELEASE]
    	at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:141) ~[spring-boot-2.2.2.RELEASE.jar:2.2.2.RELEASE]
    	at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:747) [spring-boot-2.2.2.RELEASE.jar:2.2.2.RELEASE]
    	at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:397) [spring-boot-2.2.2.RELEASE.jar:2.2.2.RELEASE]
    	at org.springframework.boot.SpringApplication.run(SpringApplication.java:315) [spring-boot-2.2.2.RELEASE.jar:2.2.2.RELEASE]
    	at org.springframework.boot.SpringApplication.run(SpringApplication.java:1226) [spring-boot-2.2.2.RELEASE.jar:2.2.2.RELEASE]
    	at org.springframework.boot.SpringApplication.run(SpringApplication.java:1215) [spring-boot-2.2.2.RELEASE.jar:2.2.2.RELEASE]
    	at cn.lenovo.ipmodify.IpmodifyApplication.main(IpmodifyApplication.java:13) [classes/:na]

     

    主要是这句话:


    You can use the -S option or python.import.site=false to not import the site module

    可以使用-S选项或python.import.site=false不导入站点模块

    像是设置 python 解释器的环境变量。

    因此在创建解释器时,设置环境变量。

    修改  JythonEnvironment 中的  getPythonInterpreter 函数

        public PythonInterpreter getPythonInterpreter(){
    
            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 inter = new PythonInterpreter();
            return inter;
        }

     

     

     

    展开全文
  • 有一个需求, 需要调用java的jar包, 因为擅长用python写程序, 那么就需要找个python包,调用java选来选取, 找到了JPypehttps://jpype.readthedocs.io/en/latest/其他包不要好用,有些需要额外在其他地方启动jvm等....
  • JAVA调用Python接口

    热门讨论 2013-02-20 10:06:13
    java调用python脚本的工具类,可以通过在java项目中导入当前的jar包,可以来调用python的脚本代码来执行python
  • I've recently discovered py4j and was able to call static java methods from python. Now I want to call python methods from java. I couldn't find much documentation so this is the last place I can thin...
  • 从Java到Python 通过http调用接口的方式实现java调用Python程序,进行数据交互
  • JAVA调用Python代码

    千次阅读 2019-05-14 16:48:49
    工程中往往会涉及多种语言的混合使用,本文记载一种常用的JAVA调用python方法。网上流传JAVA调用Python的方法有Jython,Runtime等。 1. 通过Runtime调用python脚本 我们运行python脚本的时候,通常只需在命令行敲...
  • 1. 问题描述Java平台要调用Pyhon平台已有的算法,为了减少耦合度,采用Pyhon平台提供Restful 接口Java平台负责来调用,采用Http+Json格式交互。2. 解决方案2.1 JAVA平台侧2.1.1 项目代码public static String ...
  • Java调用Python程序方法总结(最全最详细)

    万次阅读 多人点赞 2018-05-24 20:06:41
    如何使用Java调用Python程序本文为大家介绍如何java调用python方法,供大家参考。 实际工程项目中可能会用到Java和python两种语言结合进行,这样就会涉及到一个问题,就是怎么用Java程序来调用已经写好的python脚本...
  • python写的小程序,需要让java写的系统可以调用,需要是调用.py的脚本还是打包好的.exe, <p>python需要做什么 求解答 ? 求大神解答 谢谢!</p>
  • java调用python脚本

    2017-11-15 21:49:56
    java调用python真的别扭,Jython不支持第三方库,然后用了Runtime.getRuntime().exec(arr);但是这样调用也出现好多问题,最终一部分python代码用bottle写了python Rest接口。 package mnist; /** * Created ...
  • Java调用Python踩坑记录

    2019-08-15 13:49:52
    使用Java调用python时,python文件内如有读写文件的操作,其路径必须为绝对路径。如:使用pandas读取csv文件时如果使用相对路径则程序将无法正常执行。 使用Java调用python时,python文件内如果导入自定义的其他...
  • Java调用python项目实战

    万次阅读 2018-02-25 10:10:21
    项目中有用到Java调用python的需求,经过各种坑之后,根据业务需求,最终实现Java调用Python的各种情况,现在将总结如下,当然调用的也是Jython,具体原因,下面会介绍,先将代码贴出来。 这种方法是调用python文件...
  • wind客户端python接口 java调用

    千次阅读 2019-02-13 17:27:41
    之前公司业务部门提出需要做wind新债数据对比,原本做的方案是直接从...根据业务要求,查找到wind资讯端 提供的接口,有C、C#、python等其他接口,本人看一下,选择使用python来实现;大概逻辑:业务在web端业务系...
  • Java调用Python爬虫

    千次阅读 2018-04-26 12:54:00
    java调用python的爬虫程序,是一件很有意思的事情, 但解决方法大多不靠谱,作者花了两天的时间,动手实践,最终完全解决了问题 java-python Java调用Python爬虫需要解决的问题: 参数传递问题 由python脚本通过...
  • 由于 python 本身为脚本语言,且经常存在调用第三方库的情况,有的时候用 java 调用 python 不如用 python 调用 java 方便。下面就整理一下在 python 调用 java 过程中需要哪些操作。(默认是 linux 的 Ubuntu 上调...
  • 【Java】使用Java调用Python的四种方法

    千次阅读 2020-07-30 11:31:55
    写在前面 为啥一个好好的岗位是Java开发工程师要去做写python呢?因为产品经理安排的(突然多少有点明白为啥程序员和...文章目录写在前面一、在java类中直接执行python语句二、在java中直接调用python脚本三、★★★使
  • 转载自:...JPype是一个能够让 python 代码方便地调用 Java 代码的工具,从而克服了 python 在某些领域(如服务器端编程)中的不足。2.JPype与Jyth...
  • java调用python

    2017-03-02 15:01:04
    import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.File; public class test { public static void main(String[] args) throws Exception { // TODO Auto-generate
  • Java调用Python

    2021-06-23 09:43:54
    关于在Java调用Python程序的实现,根据不同的用途可以使用多种不同的方法,在这里就将在Java调用Python程序的方式做一个总结。 方法一 直接通过Runtime进行调用 /** * java通过Runtime调用Python脚本 * @par
  • 当我在用Java调用python时,我需要给python传递参数,python参数需要的类型是float,但是,在Java调用python时,传过去的参数类型是Str,此时需要将Str强转为float才能调通。
  • Grpc 实战Java 调用python

    2019-12-30 21:41:26
    主要是为了解决在java代码中调用python服务的问题,考虑到性能的要求,还是决定采用RPC协议调用 服务端 接口定义文件,注意javapython定义文件相同 syntax = "proto3"; option java_multiple_files = true; ...
  • java调用Python 传递参数

    千次阅读 2018-03-15 17:48:19
    ==Java调用Python程序最近,需要在应用中,需要使用Java程序去调用Python代码,主要有两种实现方式。一、使用Jython架包因为调用的Python代码中需要使用Json对象,开始使用jython2.5.2,发现不支持json。因此,升级...
  • JPype documentationJPype is an effort to allow python programs full access to java class libraries. This is achieved not through re-implementing Python, as Jython/JPython has done, but rather through ...
  • Python调用java接口

    千次阅读 2017-03-10 18:58:02
    python requests模块的get方法请求拿到java提供的接口中的东西(接口是返回A类信息)  re=requests.get(re_url)  process_res=json.loads((re.text)) 若得到的是类的信息的话(在python中,获得的东西放到...

空空如也

空空如也

1 2 3 4 5 ... 20
收藏数 168,226
精华内容 67,290
关键字:

java调用python接口

python 订阅
java 订阅