本指南介绍如何在测试应用程序时为 Azure AI 服务凭据设置和检索环境变量。
若要设置环境变量,请使用以下命令之一(其中 ENVIRONMENT_VARIABLE_KEY
是命名键,value
是存储在环境变量中的值)。
使用以下命令在给定输入值的情况下创建和分配持久化环境变量。
:: Assigns the env var to the value
setx ENVIRONMENT_VARIABLE_KEY "value"
在命令提示符的新实例中,使用以下命令读取环境变量。
:: Prints the env var value
echo %ENVIRONMENT_VARIABLE_KEY%
使用以下命令在给定输入值的情况下创建和分配持久化环境变量。
# Assigns the env var to the value
[System.Environment]::SetEnvironmentVariable('ENVIRONMENT_VARIABLE_KEY', 'value', 'User')
在 Windows PowerShell 的新实例中,使用以下命令读取环境变量。
# Prints the env var value
[System.Environment]::GetEnvironmentVariable('ENVIRONMENT_VARIABLE_KEY')
使用以下命令在给定输入值的情况下创建和分配持久化环境变量。
# Assigns the env var to the value
echo export ENVIRONMENT_VARIABLE_KEY="value" >> /etc/environment && source /etc/environment
在 Bash 的新实例中,使用以下命令读取环境变量。
# Prints the env var value
echo "${ENVIRONMENT_VARIABLE_KEY}"
# Or use printenv:
# printenv ENVIRONMENT_VARIABLE_KEY
提示
设置环境变量后,请重启集成开发环境 (IDE),以确保新添加的环境变量可用。
若在代码中使用环境变量,必须将其读入内存。 根据所使用的语言,使用以下代码片段之一。 这些代码片段演示了如何在给定 ENVIRONMENT_VARIABLE_KEY
的情况下获取环境变量并将该值分配给名为 value
的程序变量。
有关详细信息,请参阅 Environment.GetEnvironmentVariable
。
using static System.Environment;
class Program
{
static void Main()
{
// Get the named env var, and assign it to the value variable
var value =
GetEnvironmentVariable(
"ENVIRONMENT_VARIABLE_KEY");
}
}
有关详细信息,请参阅 getenv_s
和 getenv
。
#include <iostream>
#include <stdlib.h>
std::string GetEnvironmentVariable(const char* name);
int main()
{
// Get the named env var, and assign it to the value variable
auto value = GetEnvironmentVariable("ENVIRONMENT_VARIABLE_KEY");
}
std::string GetEnvironmentVariable(const char* name)
{
#if defined(_MSC_VER)
size_t requiredSize = 0;
(void)getenv_s(&requiredSize, nullptr, 0, name);
if (requiredSize == 0)
{
return "";
}
auto buffer = std::make_unique<char[]>(requiredSize);
(void)getenv_s(&requiredSize, buffer.get(), requiredSize, name);
return buffer.get();
#else
auto value = getenv(name);
return value ? value : "";
#endif
}
有关详细信息,请参阅 System.getenv
。
import java.lang.*;
public class Program {
public static void main(String[] args) throws Exception {
// Get the named env var, and assign it to the value variable
String value =
System.getenv(
"ENVIRONMENT_VARIABLE_KEY")
}
}
有关详细信息,请参阅 process.env
。
// Get the named env var, and assign it to the value variable
const value =
process.env.ENVIRONMENT_VARIABLE_KEY;
有关详细信息,请参阅 os.environ
。
import os
# Get the named env var, and assign it to the value variable
value = os.environ['ENVIRONMENT_VARIABLE_KEY']
有关详细信息,请参阅 environment
。
// Get the named env var, and assign it to the value variable
NSString* value =
[[[NSProcessInfo processInfo]environment]objectForKey:@"ENVIRONMENT_VARIABLE_KEY"];