简体   繁体   English

使用Runtime.exec向Python进程发送参数的解决方案

[英]The solution to send arguments to Python process using Runtime.exec

I solved this problem finally!! 我终于解决了这个问题! Now, I paste my code and notes here, in order to help others. 现在,我将代码和注释粘贴到此处,以帮助他人。

My example code is to calculate similarity score between two words. 我的示例代码是计算两个单词之间的相似度得分。 In Java, it sends two words to Python where looks up score. 在Java中,它向Python发送两个单词,在其中查找分数。 Then, Python get two arguments and print their similarity score. 然后,Python得到两个参数并打印它们的相似性分数。 At last, it reads the result of Python code in Java. 最后,它读取Java中Python代码的结果。

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']

Result: 0.819618978389 结果:0.819618978389

It just a feeling but .. I think you should have: 只是一种感觉,但是..我想你应该有:

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

instead 代替

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

argv[0] is the python script. argv [0]是python脚本。

On the other hand I'm not sure p.getInputStream() does what you mean here. 另一方面,我不确定p.getInputStream()是否符合您的意思。

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. 获得良好的Java和Python参考 ,并至少阅读与您尝试在此处使用的API相关的内容。 After that, If you still without know what to do, comeback here. 之后,如果您仍然不知道该怎么办,请回到此处。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM