如何将数据作为参数从Java传递到python脚本

时间:2018-08-22 14:55:14

标签: java python parameter-passing

我想从Java类运行脚本。 我能够使用ProcessBuilder做到这一点。 现在,我正在努力将数据作为参数传递给脚本。我可以传递字符串,但是在传递数据列表(从CSV文件读取的数据)时遇到麻烦。 我尝试过的一种方法是使用StringBuffer并将数据作为Bytes

传递
    StringBuffer sb = new StringBuffer();
    ArrayList argsList = new ArrayList();

    // append the sb from record. 
    //convert it to bytes 
    //sb.toString() contains my data with a delimiter ';'

    // sb.toString().getBytes("UTF-8").toString()

    argsList.add(0,"Continuum/anaconda3/envs/sth/python");
    argsList.add(1,"python/test.py");
    argsList.add(2,"python/test.py");
    argsList.add(3,sb.toString().getBytes("UTF-8").toString())

    ProcessBuilder builder = new ProcessBuilder(argsList);

    Process p = builder.start();

我无法将sb.toString().getBytes("UTF-8")传递给流程生成器。 我得到java.lang.ArrayStoreException

另一方面,如果我通过sb.toString(),我会得到

java.io.IOException: Cannot run program Continuum/anaconda3/envs/sth/python, CreateProcess error=206, The filename or extension is too long
add it to list of commands to process builder. 

如何阅读在python中传递的内容?

这是传递数据(第X列)的正确方法吗?

谢谢

1 个答案:

答案 0 :(得分:0)

您可以尝试以下代码::

import java.io.*;

class RunPythonCommand {
    public static void main(String [] args) {
        try {

            String prg = "import sys\nprint int(sys.argv[1])+int(sys.argv[2])\n";
            BufferedWriter out = new BufferedWriter(new FileWriter("sample_code.py"));
            out.write(prg);
            out.close();
            int param1 = 10;
            int param2 = 32;

            ProcessBuilder pb = new ProcessBuilder("python", "sample_code.py", "" + param2, "" + param1);
            Process p = pb.start();

            BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream()));
            int ret = new Integer(in.readLine()).intValue();
            System.out.println("value is : " + ret);
        } catch (Exception e) {
            System.out.println(e);
        }
    }
}

希望对您有帮助