2014-09-24 84 views
0

我找不到附加到環境變量的示例。例如,下面的代碼完全取代了PATH。可能有人幫助我追加,直接或通過展示我如何訪問當前PATH,這樣我就可以修改本身並通過全改性價值的Process追加到Scala環境變量

val out2 = Process("env", None, "PATH" -> "/usr/local/bin") 

回答

2

有:

scala> util.Properties.envOrNone("PATH") 
res0: Option[String] = Some(/home/apm/go1.1/go/bin:/home/apm/go/bin:/home/apm/bin:/usr/lib/lightdm/lightdm:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games) 

那就是:

scala> util.Properties.envOrSome("PATH", Some("")) map (p => s"$p${new sys.SystemProperties()("path.separator")}/tmp") get 
warning: there was one feature warning; re-run with -feature for details 
res5: String = /home/apm/go1.1/go/bin:/home/apm/go/bin:/home/apm/bin:/usr/lib/lightdm/lightdm:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/tmp 

我只注意到我的道路已經過時。

編輯的成語:

scala> def appendToEnv(key: String, value: String) = util.Properties.envOrNone(key) match { 
    | case Some(v) if v.nonEmpty => s"$v${System getProperty "path.separator"}$value" 
    | case _ => value 
    | } 
appendToEnv: (key: String, value: String)String 

scala> appendToEnv("PATH", "/opt") 
res0: String = /home/apm/go1.1/go/bin:/home/apm/go/bin:/home/apm/bin:/usr/lib/lightdm/lightdm:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/opt 

scala> appendToEnv("UNPATH", "/opt") 
res1: String = /opt 
+0

哇噢,正是我需要的。有趣的是你也回答了關於這個話題的其他問題:-P – Hamy 2014-09-24 03:10:54

+0

生活很有趣。我添加了我認爲更爲習慣的代碼。它也處理'Some(「」)'作爲邊緣情況。 – 2014-09-24 04:54:08