首页 > 解决方案 > Scala 中的 os.system 等价于什么?

问题描述

我正在编写一个 scala 程序,我将在其中运行系统命令,从标准输入读取输入,并将其输出写入标准输出。(所以,基本上就像在 shell 中运行命令一样。”

在python中,os.system("command")有这种行为。例如,os.system("python")在运行时打开另一个 Python REPL。

在 Scala 中,运行"python" !!似乎会运行进程并立即停止。os.system在 Scala中做等价的最简单方法是什么?我觉得这可能可以用 来完成scala.sys.process.ProcessIO,但我无法在任何地方找到任何明确的例子来说明如何做到这一点。

标签: scala

解决方案


只要您不需要它在 Scala REPL 中工作,那么!<应该就是您所需要的。

%> cat so.sc
import sys.process._
object Obj extends App {
  Seq("python3","-i").!<
}
%> scalac so.sc
%> scala Obj
Python 3.6.8 (default, Aug 20 2019, 17:12:48) 
[GCC 8.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> x = 4
>>> print('x: ' + str(x))
x: 4
>>> <CTL-D>
%> 

Python 没有在终端/TTY 环境中被调用,因此需要该-i选项来强制它进入交互模式。


推荐阅读