Groovy字符串执行与列表执行 [英] Groovy string execute versus list execute

查看:497
本文介绍了Groovy字符串执行与列表执行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望这两个表达式在stdout不为空的情况下相同:

I expected both of these to behave the same in which stdout is not empty:

assert !"bash -c \"ls *.txt\"".execute().text.empty // assertion failure here
assert !['bash', '-c', 'ls *.txt'].execute().text.empty

但他们没有。什么是语义差异?对于第一行,我怀疑Groovy发送了 [ - c,\ls,* .txt \] 作为bash的参数,但是我不确定。任何人都可以证实这一点吗?

but they do not. What are the semantic differences? For the first line I suspect Groovy is sending ["-c", "\"ls", "*.txt\""] as arguments to bash, but I'm not sure. Can anyone confirm that?

推荐答案

你的假设是正确的。请参阅thatt命令的返回码/ stderr:

Your assumption is correct. See the return code/stderr from thatt command:

groovy:000> p = "bash -c \"ls *.txt\"".execute()
===> java.lang.UNIXProcess@54eb2b70
groovy:000> p.waitFor() // exitValue()
===> 1
groovy:000> p.errorStream.readLines()
===> [*.txt": -c: line 0: unexpected EOF while looking for matching `"', *.txt": -c: line 1: syntax error: unexpected end of file]

如果您通过
https://github.com/apache/groovy/blob/GROOVY_2_4_8/src/main/org /codehaus/groovy/runtime/ProcessGroovyMethods.java#L532-L534
到JDK的

If you follow the source down via https://github.com/apache/groovy/blob/GROOVY_2_4_8/src/main/org/codehaus/groovy/runtime/ProcessGroovyMethods.java#L532-L534 into the JDK's

java.lang。运行时:exec(String命令,String [] envp,File dir)

https://docs.oracle.com/javase/7/docs/api/java/lang/Runtime.html#exec(java.lang.String,%20java.lang.String[],%20java.io.File)

你会发现, StringTokenizer 用于sp点亮该字符串/命令,从而为您的引用无效的shell。所有引用只需要shell本身而不是 ProcessBuilder

you will find, that a StringTokenizer is used to split that string/command, thus rendering your " quoting for the shell useless. After all the quoting is only needed for the shell itself and not the ProcessBuilder.

这篇关于Groovy字符串执行与列表执行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆