执行使用scala.sys.process bash的字符串 [英] Executing bash strings using scala.sys.process
问题描述
我最近发现在斯卡拉sys.process包,并通过逗乐它的力量。
但是当我尝试将它与bash的管道和反引号结合起来,我会被卡住。
这显然是行不通的:
斯卡拉> 回声`date`!
RES0:字符串=
'date`
我试图使用bash可执行文件来获得所需的行为:
斯卡拉> 庆典-e回声`date`!
/斌/回声:/斌/回声:不能执行二进制文件
了java.lang.RuntimeException:非零值:126
我在做什么错了?
编辑:
斯卡拉> 庆典-ic'回声'date`'!
`date`':意外EOF同时寻找匹配`''
`date`:语法错误:意外的文件结束
了java.lang.RuntimeException:非零值:1
您在做多件事情其实错了。你应该使用bash的-c选项,你应该使用序列[字符串]每个参数在其自己的字符串打坏,或Scala库将只拆分在每个空格字符字符串。 (这就是为什么雷克斯·科尔的解决方案是行不通的。)
斯卡拉>进口sys.process.stringSeqToProcess
进口sys.process.stringSeqToProcess斯卡拉> SEQ(庆典,-c,回声`date`)!
res20:字符串=
太阳报12月4日16时40分04秒CET 2011
I recently discovered sys.process package in Scala, and was amused by it's power.
But when I try to combine it with bash pipes and backticks, I get stuck.
This obviously doesn't work:
scala> "echo `date`" !!
res0: String = "
"`date`
"
I tried to use bash executable to get the desired behavior:
scala> "bash -e echo `date`" !!
/bin/echo: /bin/echo: cannot execute binary file
java.lang.RuntimeException: Nonzero exit value: 126
What am I doing wrong?
Edit:
scala> "bash -ic 'echo `date`'" !!
`date`': unexpected EOF while looking for matching `''
`date`': syntax error: unexpected end of file
java.lang.RuntimeException: Nonzero exit value: 1
You're doing multiple things wrong actually. You should be using the -c option of bash and you should be using a Seq[String] with each parameter to bash in its own String, or the scala library will just split the String at every space character. (This is why Rex Kerr's solution doesn't work.)
scala> import sys.process.stringSeqToProcess
import sys.process.stringSeqToProcess
scala> Seq("bash", "-c", "echo `date`")!!
res20: String =
"Sun Dec 4 16:40:04 CET 2011
"
这篇关于执行使用scala.sys.process bash的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!