如何在 Scala 中读取环境变量

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9997292/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-22 04:04:04  来源:igfitidea点击:

How to read environment variables in Scala

scalaenvironment-variables

提问by summerbulb

In Java, reading environment variables is done with System.getenv().

在 Java 中,读取环境变量是使用System.getenv().

Is there a way to do this in Scala?

有没有办法在 Scala 中做到这一点?

回答by paradigmatic

Since Scala 2.9 you can use sys.envfor the same effect:

从 Scala 2.9 开始,您可以使用sys.env相同的效果:

scala> sys.env("HOME")
res0: String = /home/paradigmatic

I think is nice to use the Scala API instead of Java. There are currently several project to compile Scala to other platforms than JVM (.NET, javascript, native, etc.) Reducing the dependencies on Java API, will make your code more portable.

我认为使用 Scala API 而不是 Java 很好。目前有几个项目可以将 Scala 编译到 JVM 以外的其他平台(.NET、javascript、native 等)。减少对 Java API 的依赖,将使您的代码更具可移植性。

回答by andy

There is an object:

有一个对象:

scala.util.Properties

this has a collection of methods that can be used to get environment info, including

这有一组可用于获取环境信息的方法,包括

scala.util.Properties.envOrElse("HOME", "/myhome" )

回答by dhg

Same way:

同样的方法:

scala> System.getenv("HOME")
res0: java.lang.String = /Users/dhg

回答by victe

Using directly a default with getOrElseover the sys.envMap (val myenv: Map[String, String] = sys.env):

直接getOrElsesys.envMap ( val myenv: Map[String, String] = sys.env) 上使用默认值:

sys.env.getOrElse(envVariable, defaultValue)

You get the content of the envVariableor, if it does not exist, the defaultValue.

您将获得 的内容envVariable,如果不存在,则获得defaultValue.

回答by jfuentes

If Lightbend's configuration library is used (by default in Play2 and Akka) then you can use

如果使用 Lightbend 的配置库(默认在 Play2 和 Akka 中)那么你可以使用

foo = "default value" foo = ${?VAR_NAME}

foo = "default value" foo = ${?VAR_NAME}

syntax to override foo if an environment variable VAR_NAME exist. More details in https://github.com/typesafehub/config#optional-system-or-env-variable-overrides

如果环境变量 VAR_NAME 存在,则覆盖 foo 的语法。https://github.com/typesafehub/config#optional-system-or-env-variable-overrides 中的更多详细信息

回答by Matthias Braun

To print allenvironment variables, you can use

要打印所有环境变量,您可以使用

System.getenv.forEach((name, value) => println(s"$name: $value"))