`

使用scala.sys.process包和系统交互

阅读更多
在Java中我们可以使用Runtime.getRuntime().exec();来和系统交互。这个API过于底层,exec返回一个代表进程的对象,然后从中读取执行结果或者错误信息。并且如果不关心进程的输出,而没有把输入结果重定向到/dev/null,超过输出结果的buffer就会阻塞。
scala.sys.process提供了shell的和系统交互的DSL,包括执行命令、逻辑操作、重定向、管道等操作。
使用!来执行外部命令:
"find project -name *.jar" !

如果没有参数,直接输出到标准输出或者标准错误输出
你可以传递Logger参数给!
"find project -name *.jar" ! log

如果想保存到变量中:
val result = "find project -name *.jar" !!

使用逻辑操作#&&,#||
cmd1 #&& cmd2
cmd1 #|| cmd2
使用管道:
cmd1 #| cmd2
例子:
"find src -name *.scala -exec grep null {} ;"  #|  "xargs test -z"  #&&  "echo null-free"  #||  "echo null detected"  !

使用重定向:
scala的重定向不仅可以从定向普通的文件,还可以把网络上的文件进行重定向到本地:
a #< url or url #> a
例子:
url("http://fuliang.iteye.com") #> file("blog.html") !
//或者
file("blog.html") #< url("http://fuliang.iteye.com") !

文件:
a #< file or file #> a
a可以是一个文件或者一个命令,比如:
file("blog.html") #> file("fuliang_blog.html") !
//或者
file("fuliang_blog.html") #< file("blog.html") !

还可以使用 #>> #<<追加操作:
a #>> file or file #<<
url("http://fuliang.iteye.com") #> "grep -i ruby" #>> file("Ruby") !
//或者
file("Ruby") #<< ( "grep ruby" #< url(http://fuliang.iteye.com") )  !

使用cat:
val spde = url("http://technically.us/spde/About")
val dispatch = url("http://databinder.net/dispatch/About")
val build = file("project/build.properties")
cat(spde, dispatch, build) #| "grep -i scala" !


当然这一切的操作时通过字符串操作和执行命令的!、!!操作符完成的。
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics