英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论