如何从我的python脚本中获取参数并从我的java项目中读取它们

时间:2019-01-31 21:27:31

标签: java python

我多次尝试将参数从python脚本获取到Java代码。 我使用sys.argv[]从Java代码中获取参数到python脚本,此操作完成了。 例如,有什么方法可以将参数从python文件发送到我的Java代码上的数组列表。 我需要处理这些论点。 我尝试了这段代码。

public static ArrayList<String> ex(String script) {
    ArrayList<String>a = new ArrayList<>();
    String[] command =
            {
                    "python",
                    script,
            };
    Process p;
    try {
        p = Runtime.getRuntime().exec(command);
        new Thread(new SyncPipe(p.getErrorStream(), System.err)).start();
        new Thread(new SyncPipe(p.getInputStream(), System.out)).start();
        //PrintWriter stdin = new PrintWriter(p.getOutputStream());
        InputStreamReader read = new InputStreamReader(p.getInputStream());
        BufferedReader r = new BufferedReader(read);
        //stdin.close();
        p.waitFor();
        String s = null;

        while((s=r.readLine())!=null){
            a.add(s);
            System.out.println("s="+s);
        }
        r.close();
        System.out.println("The size = "+a.size());


    } catch (Exception e) {
        e.printStackTrace();
    }
    return a;
}


public SyncPipe(InputStream istrm, OutputStream ostrm) {
    istrm_ = istrm;
    ostrm_ = ostrm;
}
public void run() {
    try
    {
        final byte[] buffer = new byte[1024];
        for (int length = 0; (length = istrm_.read(buffer)) != -1; )
        {
            ostrm_.write(buffer, 0, length);
        }
    }
    catch (Exception e)
    {
        e.printStackTrace();
    }

Python ...

import sys

print("Start\n\n")
sys.stdout.write("Arguments")

该进程未进入while循环,因为没有返回数据 当我单独运行python脚本或从Java代码运行时,在控制台上印有“ Arguments”一词 但是我需要在数组列表中。

0 个答案:

没有答案