在 Scala 中发出本机系统命令
我想从 Scala 程序发出本机系统命令,并可能捕获输出。 (我想到了“ls”。可能还有其他方法可以在不发出命令的情况下获取目录信息,但这不是我的问题的重点。)它对应于 Python 中的 os.system(...) 。
我看过“Scala 编程”。我看过 O'Reilly 的“Programming Scala”。我用谷歌搜索了几种术语组合。还没有运气。有人可以给我举个例子,或者指出我可以找到示例的资源吗?
I want to issue a native system command from a Scala program, and perhaps trap the output. ("ls" comes to mind. There may be other ways to get directory information without issuing the command, but that's beside the point of my question.) It would correspond to os.system(...) in Python.
I've looked in "Programming in Scala". I've looked in O'Reilly's "Programming Scala". I've Googled several combinations of terms. No luck yet. Can someone out there give me an example, or point me at a resource where I can find an example?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
最好的方法是使用 scala.sys。过程。
Best way to do that is to use scala.sys.process.
参考
reference
Scala 在这方面与 Java 没有什么不同,因为您可以使用 Scala 的互操作功能调用任何 Java API 函数。例如,请参见
java.lang .ProcessBuilder
。Scala is not different from Java in this area, since you can call any Java API functions using Scala's interop features. See for example,
java.lang.ProcessBuilder
.您可以使用 sys.process 轻松完成此操作:
执行系统命令并获取其状态代码(退出代码):
从系统命令获取输出:
您还有其他几个选项(管道、重定向 STDOUT、附加到 STDOUT 等),您可以看到 此链接。
You can do it using
sys.process
easily:Executing system commands and getting their status code (exit code):
Getting output from system commands:
You have several other options (pipeline, Redirect STDOUT, Append to STDOUT and ...), you can see this link.
Scala 与 Java 具有完全的互操作性。因此,您可以像从 Java 中一样从 Scala 中调用系统命令。请参阅此了解如何从 Java 调用系统命令。
Scala has complete interoperability with Java. So you can call the system commands from Scala as you would from Java. See this to see how to call system commands from Java.