【问题标题】:Scala - shell commands with pipeScala - 带管道的 shell 命令
【发布时间】:2012-10-08 14:34:02
【问题描述】:

我是 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”)。

您能否建议我,如何正确执行此操作?

【问题讨论】:

  • @xhochy 好的。我删除了评论,这样任何人都不会意外使用它。 :)

标签: scala


【解决方案1】:

改变

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" !

【讨论】:

  • 不幸的是它没有用。我收到此错误:-eF:-c:第 0 行:在寻找匹配的 `'' 时出现意外 EOF -eF:-c:第 1 行:语法错误:文件意外结束
  • @altanis 哦,Scala 似乎有时会删除 ' 勾号。我用一个应该可以工作的解决方案更新了我的答案(我认为最好的办法是使用 Scala 魔法,将管道作为函数输入(最后一个示例)。
  • @altanis - 似乎您的命令中有多余的引号。尝试打印directory.getAbsolutePath + ";" + command 输出,也许可以解决它。
  • @Rogach altanis 的第一条评论指的是我的旧答案。在更新版本中,这个问题应该消失了。
  • @xhochy 谢谢,现在它可以正常工作了。我唯一改变的是:/bin/bash -> /bin/sh.
猜你喜欢
  • 2016-06-26
  • 1970-01-01
  • 2013-07-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多