Scala.sys package This package containg various routines supporting:
Java has System class. Part of this functionality
has been copied to scala.sys package
Shutdown hook If you want to react for JVM shutdown event, then you need to add shutdown hook to application
scala.sys.addShutdownHook(shutdown_method)Example
object Application extends App {
def shutdown = "Bye world"
sys addShutdownHook(shutdown)
}
Exit JVM with exit code
sys.exit -1
System Properties Mutable map
sys.props("java.version") //1.7.0_25 (result)
Runtime
does the same as java.lang.Runtime.getRuntime()
sys.runtime
scala.sys.runtime.freeMemory //31260800 (result)Communication with external processes Prerequisites
import scala.sys.process._Run process and get exit code
"java -version"! //0 (result)Get output from process as String
"echo Hello world"!! //Hello world (result)Get output from process as Stream of String
val cmd = "ping 127.0.0.1" val stream : Stream[String]= cmd.lines_! stream.toList //convert to listOutput
Pinging 127.0.0.1 with 32 bytes of data: Reply from 127.0.0.1: bytes=32 time<1ms TTL=128 Reply from 127.0.0.1: bytes=32 time<1ms TTL=128 Reply from 127.0.0.1: bytes=32 time<1ms TTL=128 Reply from 127.0.0.1: bytes=32 time<1ms TTL=128 Ping statistics for 127.0.0.1: Packets: Sent = 4, Received = 4, Lost = 0 (0% loss), Approximate round trip times in milli-seconds: Minimum = 0ms, Maximum = 0ms, Average = 0ms
Run commands sequentially
"echo A" ### "echo B" ### "echo C" !!Output
A B C
Run commands conditionally
"ping google.com" #&& "echo machine ok" #|| "echo connection failed" !!Output
Pinging google.com [46.28.247.88] with 32 bytes of data: Reply from 46.28.247.88: bytes=32 time=7ms TTL=59 Reply from 46.28.247.88: bytes=32 time=6ms TTL=59 Reply from 46.28.247.88: bytes=32 time=9ms TTL=59 Reply from 46.28.247.88: bytes=32 time=5ms TTL=59 Ping statistics for 46.28.247.88: Packets: Sent = 4, Received = 4, Lost = 0 (0% loss), Approximate round trip times in milli-seconds: Minimum = 5ms, Maximum = 9ms, Average = 6ms machine ok
"ping bad_host" #&& "echo machine ok" #|| "echo connection failed" !!Output
Ping request could not find host bad_host. Please check the name and try again. connection failed
Run commands in pipeline
"ping 127.0.0.1" #| "grep Lost" !!Output
Packets: Sent = 4, Received = 4, Lost = 0 (0% loss),
Passing input/output of process
import java.io._Provide input for process: "#<" operator
val inputText = "Hello world"
//convert string to inputstream
val inputStream =
new ByteArrayInputStream(inputText.getBytes("utf-8"))
//provide input stream as input of process
"cat" #< inputStream !!
Output
Hello world
Take output of process: "#>" operator
//redirect output of process to stream
val outputStream = new ByteArrayOutputStream
"echo Hello world" #> outputStream !!
val output = new String(outputStream.toByteArray)
output
Output
Hello world
No comments:
Post a Comment