如何在Nox会话中传递并使用环境变量?
问题解答:用Nox传递本地环境变量到虚拟环境
可行性结论
完全可行,Nox支持多种方式将本地环境变量传递到其创建的虚拟环境中,以下针对你的场景给出具体实现方法。
方法1:在session.run()中通过env参数传递
这是最常用的方式,适合在执行特定命令(比如pytest)时精准传递环境变量。你可以选择从本地环境直接读取变量,或者从命令行参数中解析后传入。
示例代码修改(适配你的需求)
场景1:从本地环境变量读取EE_DECRYPT_KEY
import os import nox @nox.session(name="test", python="3.8") def test(session): # 安装虚拟环境依赖 if _should_install(session): session.install(".[test]") # 针对SEPAL环境安装特定版本的earthengine API if "sepal" in session.posargs: session.posargs.remove("sepal") session.install("git+https://github.com/custom_lib") # 复制本地环境变量,避免修改原始环境 test_env = os.environ.copy() # 可选:如果需要强制设置变量值,直接修改字典即可 # test_env["EE_DECRYPT_KEY"] = "your_custom_key" # 运行测试时传递环境变量 session.run("pytest", *session.posargs, env=test_env)
场景2:从命令行参数中解析EE_DECRYPT_KEY
如果需要通过nox命令行传递密钥(比如执行nox -s test EE_DECRYPT_KEY=abc123),可以先解析参数再传入:
import os import nox @nox.session(name="test", python="3.8") def test(session): # 分离posargs中的环境变量参数和pytest参数 env_vars = {} filtered_posargs = [] for arg in session.posargs: if "=" in arg: key, value = arg.split("=", 1) env_vars[key] = value else: filtered_posargs.append(arg) session.posargs = filtered_posargs # 安装虚拟环境依赖 if _should_install(session): session.install(".[test]") # 针对SEPAL环境安装特定版本的earthengine API if "sepal" in session.posargs: session.posargs.remove("sepal") session.install("git+https://github.com/custom_lib") # 合并本地环境变量和解析到的变量 test_env = os.environ.copy() test_env.update(env_vars) # 运行测试 session.run("pytest", *session.posargs, env=test_env)
方法2:设置session.env作用于整个Session
如果希望环境变量在整个Session的所有命令(比如安装依赖、运行测试)中都生效,可以直接设置session.env属性:
import os import nox @nox.session(name="test", python="3.8") def test(session): # 将本地环境中的EE_DECRYPT_KEY注入到Session全局环境 session.env["EE_DECRYPT_KEY"] = os.environ.get("EE_DECRYPT_KEY", "") # 安装依赖时,环境变量已生效 if _should_install(session): session.install(".[test]") # 针对SEPAL环境安装特定版本的earthengine API if "sepal" in session.posargs: session.posargs.remove("sepal") session.install("git+https://github.com/custom_lib") # 运行测试无需再单独传递env参数 session.run("pytest", *session.posargs)
注意事项
- 使用
os.environ.copy()可以避免修改本地原始环境变量,保证测试环境的隔离性。 - 敏感密钥不要硬编码到代码中,优先从本地环境或安全配置源读取。
- 从命令行解析参数时,要注意区分普通pytest参数和环境变量参数,避免影响测试命令的正常执行。
内容的提问来源于stack exchange,提问作者Pierrick Rambaud
相关产品推荐
相关产品推荐

