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

2024-09-26 22:54:47 发布

您现在位置:Python中文网/ 问答频道 /正文

我曾多次尝试将python脚本中的参数获取到java代码中。 我使用sys.argv[]从java代码中获取参数到python脚本,就完成了。 例如,在我的java代码中,是否有任何方法可以将python文件中的参数发送到数组列表。 我需要处理这些论点。 我试过这个密码。你知道吗

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代码运行python脚本时,控制台中打印的单词“Arguments” 但我需要它在数组列表中。你知道吗


Tags: 代码脚本newread参数stringsysjava

热门问题