在 Scala 中发出本机系统命令

发布于 2024-09-06 17:27:06 字数 222 浏览 2 评论 0原文

我想从 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

萧瑟寒风 2024-09-13 17:27:06

最好的方法是使用 scala.sys。过程

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

╰◇生如夏花灿烂 2024-09-13 17:27:06
import scala.sys.process._

val vimLocation: String = "whereis vim" !!

参考

import scala.sys.process._

val vimLocation: String = "whereis vim" !!

reference

伴梦长久 2024-09-13 17:27:06

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.

白云悠悠 2024-09-13 17:27:06

您可以使用 sys.process 轻松完成此操作:

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

import sys.process._

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

从系统命令获取输出:

import sys.process._

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

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

You can do it using sys.process easily:

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.

寄意 2024-09-13 17:27:06

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文