Java将args传递给Python脚本

注意:python.exe的路径已经设置

我正在尝试创建一个将变量args(或任何其他变量)传递给Python脚本的Java程序

import java.io.*;

public class PythonCallTest{

    public static void main (String[] args){
        String s = null;

        Runtime r = Runtime.getRuntime();
        try{
            Process p = r.exec("cmd /c python ps.py+",args);

            BufferedReader stdInput = new BufferedReader(new
                InputStreamReader(p.getInputStream()));

            BufferedReader stdError = new BufferedReader(new
                InputStreamReader(p.getErrorStream()));

            while ((s = stdInput.readLine()) != null){
                System.out.println(s);
            }

            while ((s = stdError.readLine()) != null){
                System.out.println(s);
            }

            System.exit(0);
        }
        catch(IOException ioe){
            ioe.printStackTrace();
            System.exit(-1);
        }
    }
}

该程序可以编译,但是当我用

java PythonCallTest sender-ip=10.10.10.10

我得到了错误

无法将“ python”识别为内部或外部命令,可操作程序或批处理文件。

如何正确连接r.exec(“ cmd / c python ps.py +”,args)中的字符串

编辑

如果我执行以下

Process p = r.exec("cmd /c python ps.py sender-ip=10.251.22.105");

然后程序开始工作。python.exe的路径已经设置。我只需要知道如何添加ARGS到r.exec,即如何连接CMD / C蟒蛇ps.py与ARGS

杰米·科伯恩(Jamie Cockburn)

您正在通过args作为的第二个参数Runtime.exec(...)

这会覆盖新进程的默认(继承)环境,使其无用,因此Path变量不再包含的路径python.exe

您需要使用以下版本Runtime.exec(...)

public Process exec(String[] cmdarray);

您将这样做:

public static void main(String[] args) {
    ...

    List<String> process_args = new ArrayList<String>(Arrays.asList("cmd", "/c", "python", "ps.py"));
    process_args.addAll(Arrays.asList(args));

    Runtime r = Runtime.getRuntime();
    try {

        Process p = r.exec(process_args.toArray(new String[] {}));
        ...
    } catch (IOException e) {
        ...
    }
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章