Scala 2.9 中的“scala.sys.process"是如何工作的? [英] How does the “scala.sys.process” from Scala 2.9 work?

查看:37
本文介绍了Scala 2.9 中的“scala.sys.process"是如何工作的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚查看了新的 scala.sysscala.sys.process 包,看看这里是否有帮助.然而,我完全不知所措.

I just had a look at the new scala.sys and scala.sys.process packages to see if there is something helpful here. However, I am at a complete loss.

有没有人有关于如何实际启动流程的示例?

Has anybody got an example on how to actually start a process?

而且,对我来说最有趣的是:你能分离进程吗?

And, which is most interesting for me: Can you detach processes?

分离的进程会在父进程结束时继续运行,这是 Ant 的弱点之一.

A detached process will continue to run when the parent process ends and is one of the weak spots of Ant.

更新:

分离是什么似乎有些混乱.从我当前的项目中获得一个真实的例子.一次使用 z-Shell,一次使用 TakeCommand:

There seem to be some confusion what detach is. Have a real live example from my current project. Once with z-Shell and once with TakeCommand:

Z-Shell:

if ! ztcp localhost 5554; then
    echo "[ZSH] Start emulator"
    emulator                        \
    -avd    Nexus-One               \
    -no-boot-anim                   \
    1>~/Library/Logs/${PROJECT_NAME}-${0:t:r}.out   \
    2>~/Library/Logs/${PROJECT_NAME}-${0:t:r}.err   &
    disown
else
    ztcp -c "${REPLY}"
fi;

接受命令:

IFF %@Connect[localhost 5554] lt 0 THEN
   ECHO [TCC] Start emulator
   DETACH emulator -avd Nexus-One -no-boot-anim
ENDIFF

在这两种情况下,它都是一劳永逸的,模拟器已启动,即使在脚本结束后也会继续运行.当然,必须编写两次脚本是一种浪费.因此,我现在开始研究 Scala,以实现无需 cygwin 或 xml 语法的统一流程处理.

In both cases it is fire and forget, the emulator is started and will continue to run even after the script has ended. Of course having to write the scripts twice is a waste. So I look into Scala now for unified process handling without cygwin or xml syntax.

推荐答案

首次导入:

import scala.sys.process.Process

然后创建一个 ProcessBuilder

then create a ProcessBuilder

val pb = Process("""ipconfig.exe""")

那么你有两个选择:

  1. 运行并阻塞直到进程退出

  1. run and block until the process exits

val exitCode = pb.!

  • 在后台运行该进程(分离)并获得一个 Process 实例

    val p = pb.run
    

    然后你可以从进程中获取退出代码(如果进程仍在运行它会阻塞直到它退出)

    Then you can get the exitcode from the process with (If the process is still running it blocks until it exits)

    val exitCode = p.exitValue
    

  • 如果要处理进程的输入输出可以使用ProcessIO:

    If you want to handle the input and output of the process you can use ProcessIO:

    import scala.sys.process.ProcessIO
    val pio = new ProcessIO(_ => (),
                            stdout => scala.io.Source.fromInputStream(stdout)
                              .getLines.foreach(println),
                            _ => ())
    pb.run(pio)
    

    这篇关于Scala 2.9 中的“scala.sys.process"是如何工作的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆