如何从Scala执行Shell内置的Shell [英] How to execute shell builtin from Scala

查看:597
本文介绍了如何从Scala执行Shell内置的Shell的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要从Linux的Scala脚本中检查一些系统设置,例如ulimit -n.如果我要处理普通命令,我会使用scala.sys.process包,例如:

I need to check some system settings like ulimit -n from Scala script in Linux. Had I to deal with ordinary commands I would use scala.sys.process package like:

import scala.sys.process._
println("ls -lha".!!)

不幸的是,这不适用于shell内置程序.有什么方法可以从Scala内置的shell中捕获输出吗?

Unfortunately this doesn't work for shell builtins. Is there any way to catch an output from shell builtin in Scala?

更新:

我以几种形式尝试了通常的把戏sh -c "ulimit -n",但没有运气;以下所有命令均失败:

I tried the usual trick sh -c "ulimit -n" in several forms with no luck; All the commands below fail:

"sh -c 'ulimit -n'".!!
"sh -c \"ulimit -n\"".!!
"""sh -c "ulimit -n"""".!!
"""sh -c "ulimit -n """ + "\"".!!

我在REPL中遇到运行时错误:

And I'm getting a runtime error in REPL:

-n": 1: Syntax error: Unterminated quoted string
java.lang.RuntimeException: Nonzero exit value: 2
    at scala.sys.package$.error(package.scala:27)
    at scala.sys.process.ProcessBuilderImpl$AbstractBuilder.slurp(ProcessBuilderImpl.scala:131)
    at scala.sys.process.ProcessBuilderImpl$AbstractBuilder.$bang$bang(ProcessBuilderImpl.scala:101)
    at .<init>(<console>:11)
    at .<clinit>(<console>)
    at .<init>(<console>:11)
    at .<clinit>(<console>)
    at $print(<console>)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:601)
    at scala.tools.nsc.interpreter.IMain$ReadEvalPrint.call(IMain.scala:704)
    at scala.tools.nsc.interpreter.IMain$Request$$anonfun$14.apply(IMain.scala:920)
    at scala.tools.nsc.interpreter.Line$$anonfun$1.apply$mcV$sp(Line.scala:43)
    at scala.tools.nsc.io.package$$anon$2.run(package.scala:25)
    at java.lang.Thread.run(Thread.java:722)

推荐答案

将字符串转换为shell命令时,参数之间用空格分隔.您尝试使用的约定是 shell 约定,因此您首先需要一个shell才能应用它们.

When strings are converted to a shell command, parameters are separated by space. The conventions you tried are shell conventions, so you'd need a shell to begin with to apply them.

如果要进一步控制每个参数的含义,请使用Seq[String]而不是String,或者使用具有相同含义的Process工厂之一.例如:

If you want more control over what each parameter is, use a Seq[String] instead of a String, or one of the Process factories that amount to the same thing. For example:

Seq("sh", "-c", "ulimit -n").!!

这篇关于如何从Scala执行Shell内置的Shell的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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