使用Runtime.exec向Python进程发送参数的解决方案 [英] The solution to send arguments to Python process using Runtime.exec

查看:130
本文介绍了使用Runtime.exec向Python进程发送参数的解决方案的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我终于解决了这个问题!现在,我将代码和注释粘贴到此处,以帮助他人.

I solved this problem finally!! Now, I paste my code and notes here, in order to help others.

我的示例代码是计算两个单词之间的相似度得分.在Java中,它向Python发送两个单词,在其中查找得分.然后,Python获得两个参数并打印它们的相似性分数.最后,它读取Java中Python代码的结果.

My example code is to calculate similarity score between two words. In Java, it sends two words to Python where looks up score. Then, Python get two arguments and print their similarity score. At last, it reads the result of Python code in Java.

Java:

    import java.io.*;

    public class RuntimeTest
    {
    public static void main(String[] args)
    { 
    try 
    {
    Runtime r = Runtime.getRuntime();


    String[] cmd={"/usr/bin/python",
            "/home/parallels/Desktop/.../src/ConceptNetSimilarity.py",
            "cat",
            "dog"}; 

    Process p = r.exec(cmd);

    #exec(String[] cmd) - cmd[0]:path of python-3.x cmd[1]:path of your python code cmd[2],[3]:arguments  
    #if you only invoke python code without arguments, `Process p = r.exec("python path-of-your-code");` instead.    

    p.waitFor();
    BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
    String line = "";
    while ((line = br.readLine()) != null)
    {
        System.out.println(line);
    }
    p.waitFor();
    } 
    catch (Exception e) 
    {
    e.printStackTrace();
    }
    }
    }

Python:

import sys
import divisi2 
assoc = divisi2.network.conceptnet_assoc('en')
U, S, _ = assoc.svd(k=100)
spread = divisi2.reconstruct_activation(U, S)
print spread.entry_named(sys.argv[1],sys.argv[2])  
#argv=['/home/parallels/Desktop/.../src/ConceptNetSimilarity.py', 'cat', 'dog']

结果: 0.819618978389

Result: 0.819618978389

推荐答案

只是一种感觉,但是..我认为您应该拥有:

It just a feeling but .. I think you should have:

print spread.entry_named(sys.argv[1],sys.argv[2])

代替

print spread.entry_named(sys.argv[0],sys.argv[1])

argv [0]是python脚本.

argv[0] is the python script.

另一方面,我不确定p.getInputStream()是否符合您的意思.

On the other hand I'm not sure p.getInputStream() does what you mean here.

一个好的建议? 获得良好的Java和Python参考,并至少阅读与您尝试在此处使用的API相关的内容.之后,如果您仍然不知道该怎么办,请回到此处.

One good advice? Get a good Java and Python reference and at least read the content related with the API you are trying to use here. After that, If you still without know what to do, comeback here.

这篇关于使用Runtime.exec向Python进程发送参数的解决方案的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆