简体   繁体   English

在 VSCode 中运行 Python 单元测试时设置环境变量

[英]Setting environment variable when running Python unit tests inside VSCode

I'd like to execute code inside my unit tests conditioned on whether they're running from within VSCode or the command line.我想在我的单元测试中执行代码,条件是它们是在 VSCode 中还是在命令行中运行。 Is there a way to do so?有没有办法这样做?

The reasoning is to add additional visual feedback through cv2.imwrite statements, but to omit these when running a full regression from the command line or when running my CI.原因是通过cv2.imwrite语句添加额外的视觉反馈,但在从命令行运行完整回归或运行我的 CI 时省略这些。

I known that I can set a debugging profile inside launch.json and define environment variables there, but this applies only when debugging a unit test:我知道我可以在launch.json中设置调试配置文件并在那里定义环境变量,但这仅适用于调试单元测试时:

       {
            "name": "Debug Tests",
            "type": "python",
            "request": "test",
            "console": "integratedTerminal",
            "python": "${command:python.interpreterPath}",
            "justMyCode": false,
            "env": {
                "MY_ENVIRONMENT_SWITCH_FOR_WRITING_JPEGS": "1"
            }
        },

Is there a way to achieve something similar when not running through the debugger?有没有办法在不通过调试器运行时实现类似的东西?

Try defining environment variables by using .env files尝试使用.env文件定义环境变量

在此处输入图像描述

.env : .env

MY_ENVIRONMENT_SWITCH_FOR_WRITING_JPEGS = 1

test1.py :测试1.py

import os
from pathlib import Path
from dotenv import find_dotenv, load_dotenv

env_path = Path(".") / ".env"
load_dotenv(dotenv_path=env_path, verbose=True)
print(os.getenv("MY_ENVIRONMENT_SWITCH_FOR_WRITING_JPEGS"))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM