0

I am executing a python script from Java using Process approach. I have this code part where I have a StringBuilder with following structure:(val1,val2,...).

Now I have this part of code which uses Process approach to execute the python scripts from within Java code:

ProcessBuilder pb = new ProcessBuilder("python","test1.py");
Process p = pb.start();

BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream()));
int ret = new Integer(in.readLine()).intValue();

Now what I want is to first check if my StringBuilder str is empty or not i.e. the string is just () and there is nothing inside () in str. If it is not empty (i.e. there are values inside ()) then I need to pass each value as a separate parameter with the Process call for my python script. For example if my str is (val1,val2) then I need to pass val1 and val2 as a separate parameters in the Process call for executing the python script from within Java code.

How can I modify my current code to include this?

user2966197
  • 2,793
  • 10
  • 45
  • 77

1 Answers1

0

Why use a StringBuilder at all instead of just passing your arguments along?

new ProcessBuilder("python", "test1.py", "val1", "val2")

You can dynamically create that parameter array if necessary.

List<String> args = new ArrayList<>();
args.add("python");
args.add("test1.py");
args.addAll(myOtherArgsThatICollectedInAList);
new ProcessBuilder(args.toArray(new String[0]);
Thilo
  • 257,207
  • 101
  • 511
  • 656
  • Theres a long code before the code I have posted which is forming the `StringBuilder`. So using it is necessity. – user2966197 Oct 28 '15 at 07:46
  • One can always refactor. If not, you'll have to split your long string by comma (which might be error-prone). – Thilo Oct 28 '15 at 07:48
  • The way I have shown the `StringBuilder` is emphasize on the structure of the StringBuilder getting formed. The actual code that is forming is not the one I have shown. Its more of a representation – user2966197 Oct 28 '15 at 07:49
  • can you show how to do it? My StringBuilder structure will always be `(val1,val2)` or just `()` if there is no `val` coming in. – user2966197 Oct 28 '15 at 07:50
  • http://stackoverflow.com/questions/10631715/how-to-split-a-comma-separated-string?rq=1 – Thilo Oct 28 '15 at 07:52
  • based on the answer in the link it will produce a list of strings. How can I then pass each element of that list as a parameter in a Process call? – user2966197 Oct 28 '15 at 13:05
  • Just one more doubt. My StringBuilder has structure `(val1,val2...)`. So if I do split(",") it will split at `,` but theres extra `(` and `)` at the beginning and ending of the StringBuilder. How can I remove those so that `myOtherArgsThatICollectedInAList ` only has `val1`,`val2` and so on? – user2966197 Oct 29 '15 at 03:35
  • throw away the first and the last character ? – Thilo Oct 29 '15 at 06:25