简体   繁体   中英

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. 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.

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:

       {
            "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 :

MY_ENVIRONMENT_SWITCH_FOR_WRITING_JPEGS = 1

test1.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"))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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