Scala – 带管道的shell命令
发布时间:2020-12-16 18:18:26 所属栏目:安全 来源:网络整理
导读:我是一个 Scala初学者,我正在编写一个用于调用shell命令的包装器.目前我正在尝试使用指定目录中的管道调用shell命令. 为了达到这个目的,我编写了一个简 def runCommand(command: String,directory: File): (Int,String,String) = { val errbuffer = new Stri
我是一个
Scala初学者,我正在编写一个用于调用shell命令的包装器.目前我正在尝试使用指定目录中的管道调用shell命令.
为了达到这个目的,我编写了一个简 def runCommand(command: String,directory: File): (Int,String,String) = { val errbuffer = new StringBuffer(); val outbuffer = new StringBuffer(); //run the command val ret = sys.process.Process(command,directory) ! //log output and err ProcessLogger(outbuffer append _ + "n",outbuffer append _ + "n"); return (ret,outbuffer.toString(),errbuffer.toString()); } 但是使用此实用程序我不能使用管道,例如: runCommand("ps -eF | grep -i foo",new File(".")); 首先我想,管道是shell的功能,所以我尝试了“/ bin / sh -c ps -eF | grep -i foo”,但似乎忽略了管道右侧的表达式. 我也尝试过运行命令!语法(sys.process._包),但我无法弄清楚,如何从指定目录调用命令(不使用“cd”). 能否请您指教,如何正确地做到这一点? 解决方法
更改
val ret = sys.process.Process(command,directory) ! 至 val ret = sys.process.stringSeqToProcess(Seq("/bin/bash","-c","cd " + directory.getAbsolutePath + ";" + command)) 或者您可以直接使用Scala提供的魔力: import.scala.sys.process._ val ret = "ps -ef" #| "grep -i foo" ! (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |