Java运行时问题:传递包含空格的参数?

huangapple go评论178阅读模式
英文:

Java Runtime issue with passing arguements which includes spaces?

问题

I have a python program where i am taking arguments from command line, the following python script will be run using JAVA code with runtime,

From Ubuntu Terminal:

import sys
print(sys.argv[1])

It's print's My String With Spaces

Java Code:

Process p = Runtime.getRuntime().exec("python3 testingArg.py \"My String With Spaces\"");
BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream()));
while((s = in.readLine())!=null) {
    System.out.println(s);
}

Print's out as "My", and the rest of the string is truncated.

英文:

I have a python program where i am taking arguments from command line, the following python script will be run using JAVA code with runtime,

From Ubuntu Terminal :

python3 testingArg.py "My String With Spaces"


Import sys
print(sys.argv[1])

It's print's My String With Spaces

Java Code:

Process p = Runtime.getRuntime().exec("python3 testingArg.py "+"\"My String With Spaces\"");
		BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream()));
		while((s = in.readLine())!=null) {
			System.out.println(s);
		}

Print's out as "My", and the rest of the string is truncated.

答案1

得分: 1

The command string is tokenized into arguments using a default tokenizer, which splits on whitespace only - no consideration is given to quotes.

In my opinion you are better off doing the tokenization yourself (which is trivial since you know you have one argument, so there's no code required) and using the array form of exec.

String args[] = { "python3", "testingArg.py", "My String With Spaces" };
Runtime.getRuntime().exec(args);

The "command string" form that you're currently using is essentially tokenizing the string into an array for you, but it's using an algorithm you're not happy with, so skip that and make the appropriate array yourself.

英文:

The command string is tokenized into arguments using a default tokenizer, which splits on whitespace only - no consideration is given to quotes.

In my opinion you are better off doing the tokenization yourself (which is trivial since you know you have one argument, so there's no code required) and using the array form of exec.

String args[] = { "python3",  "testingArg.py" , "My String With Spaces" };
Runtime.getRuntime().exec(args);

The "command string" form that you're currently using is essentially tokenizing the string into an array for you, but it's using an algorithm you're not happy with, so skip that and make the appropriate array yourself.

huangapple
  • 本文由 发表于 2020年8月12日 19:49:05
  • 转载请务必保留本文链接:https://go.coder-hub.com/63375910.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定