在树莓派 Pico W 上实现环境变量管理可以通过创建一个配置文件或使用字典来存储和管理环境变量。这些环境变量可以用于控制程序的行为、存储配置信息等。
方法 1: 使用字典管理环境变量
可以使用 Python 的字典来存储和管理环境变量。这种方法简单直接,适合小型项目。
# 创建一个字典来存储环境变量
environment_variables = {
"SSID": "your_SSID",
"PASSWORD": "your_PASSWORD",
"API_URL": "http://api.example.com/data",
}
def get_env_variable(key):
return environment_variables.get(key, None)
def set_env_variable(key, value):
environment_variables[key] = value
def display_env_variables():
print("Current Environment Variables:")
for key, value in environment_variables.items():
print(f"{key}: {value}")
# 示例使用
display_env_variables()
# 修改某个环境变量
set_env_variable("SSID", "new_SSID")
print("\nAfter updating SSID:")
display_env_variables()
方法 2: 使用配置文件管理环境变量
您可以将环境变量存储在一个文件中(如 JSON 或 INI 文件),并在程序启动时读取这些值。这种方法适合需要更复杂配置的项目。
2.1 使用 JSON 文件
首先,需要一个 JSON 文件来存储环境变量,例如 config.json。
{
"SSID": "your_SSID",
"PASSWORD": "your_PASSWORD",
"API_URL": "http://api.example.com/data"
}
然后,在代码中读取这个文件。
import json
import os
# 读取配置文件
def load_environment_variables(filename):
if os.path.exists(filename):
with open(filename, "r") as f:
return json.load(f)
else:
print("Config file not found.")
return {}
# 保存配置到文件
def save_environment_variables(filename, env_vars):
with open(filename, "w") as f:
json.dump(env_vars, f, indent=4)
# 示例使用
config_file = "config.json"
environment_variables = load_environment_variables(config_file)
# 显示环境变量
def display_env_variables(env_vars):
print("Current Environment Variables:")
for key, value in env_vars.items():
print(f"{key}: {value}")
display_env_variables(environment_variables)
# 修改某个环境变量并保存
environment_variables["SSID"] = "new_SSID"
save_environment_variables(config_file, environment_variables)
print("\nUpdated environment variables saved.")
方法 3: 使用 INI 文件
您还可以使用 INI 文件来存储环境变量,使用 configparser 模块来读取和写入。
3.1 创建 INI 文件
[DEFAULT]
SSID = your_SSID
PASSWORD = your_PASSWORD
API_URL = http://api.example.com/data
读取它
import configparser
import os
# 读取配置文件
def load_environment_variables(filename):
if os.path.exists(filename):
config = configparser.ConfigParser()
config.read(filename)
return config['DEFAULT']
else:
print("Config file not found.")
return {}
# 保存配置到文件
def save_environment_variables(filename, env_vars):
config = configparser.ConfigParser()
config['DEFAULT'] = env_vars
with open(filename, 'w') as configfile:
config.write(configfile)
# 示例使用
config_file = "config.ini"
environment_variables = load_environment_variables(config_file)
# 显示环境变量
def display_env_variables(env_vars):
print("Current Environment Variables:")
for key, value in env_vars.items():
print(f"{key}: {value}")
display_env_variables(environment_variables)
# 修改某个环境变量并保存
environment_variables['SSID'] = 'new_SSID'
save_environment_variables(config_file, environment_variables)
print("\nUpdated environment variables saved.")
总结
字典:适合小型项目,不需要持久化。
JSON 文件:适合中型项目,提供易读性和结构化。
INI 文件:适合需要分组配置的情况。