简体   繁体   中英

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

Result: 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.

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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