在 Scala 中发出本机系统命令

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3064994/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-22 02:14:00  来源:igfitidea点击:

Issuing native system commands in Scala

scalasystemcommand

提问by Tony

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.

我想从 Scala 程序发出本机系统命令,并可能捕获输出。(想到“ls”。可能还有其他方法可以在不发出命令的情况下获取目录信息,但这不是我的问题的重点。)它对应于 Python 中的 os.system(...)。

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?

我看过“Scala 编程”。我看过 O'Reilly 的“Programming Scala”。我在谷歌上搜索了几种术语组合。还没有运气。有人可以给我一个例子,或者指出我可以找到一个例子的资源吗?

回答by Daniel C. Sobral

Best way to do that is to use scala.sys.process.

最好的方法是使用scala.sys.process

回答by Johan Prinsloo

import scala.sys.process._

val vimLocation: String = "whereis vim" !!

reference

参考

回答by Saeed Zarinfam

You can do it using sys.processeasily:

您可以sys.process轻松使用:

Executing system commands and getting their status code (exit code):

执行系统命令并获取它们的状态代码(退出代码):

import sys.process._

val result = "your_command" !
println("result = "+result) // result contain zero for success or non zero for fail

Getting output from system commands:

从系统命令获取输出:

import sys.process._

val result = "your_command" !!
println("result = "+result) // result contain output from the command

You have several other options (pipeline, Redirect STDOUT, Append to STDOUT and ...), you can see this link.

您还有其他几个选项(管道、重定向 STDOUT、附加到 STDOUT 和...),您可以查看此链接

回答by Greg Hewgill

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.

Scala 在这方面与 Java 没有什么不同,因为您可以使用 Scala 的互操作功能调用任何 Java API 函数。例如,参见java.lang.ProcessBuilder

回答by Abhinav Sarkar

Scala has complete interoperability with Java. So you can call the system commands from Scala as you would from Java. See thisto see how to call system commands from Java.

Scala 与 Java 具有完全的互操作性。因此,您可以像从 Java 一样从 Scala 调用系统命令。请参阅此内容以了解如何从 Java 调用系统命令。