Java to pass args to a Python script

。_饼干妹妹 提交于 2019-12-25 03:29:27

问题


NOTE: Path of python.exe has already been set

I am trying to create a Java program that passes the variable args (or any other variable) to a Python script.

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);
        }
    }
}

The program compiles but when I run it with

java PythonCallTest sender-ip=10.10.10.10

I get the error

'python' is not recognized as an internal or external command, operable program or batch file.

How do I properly concatenate the string in r.exec("cmd /c python ps.py+",args)

EDIT

If I execute the following

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

Then the program works. The path for python.exe has already been set. I just need to know how to add args to r.exec, i.e how to concatenate cmd /c python ps.py with args


回答1:


You are passing args as the second argument of Runtime.exec(...).

This overrides the default (inherited) environment of the new process to be useless, and hence the Path variable no longer contains the path to python.exe.

You need to use this version of Runtime.exec(...):

public Process exec(String[] cmdarray);

Which you would do so like this:

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) {
        ...
    }
}


来源:https://stackoverflow.com/questions/24512412/java-to-pass-args-to-a-python-script

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!