简体   繁体   中英

Use environment variable in python command

I have a Python script that interrogates a thermocouple HAT connected to a Raspberry Pi. I am now trying to use .env files so that I can use the same script across multiple systems.

I'm having problem with one section of code where the environment variable is used within a method (sorry, not sure if that is the right term).

This is the code before I try to add the environment variable:

from dotenv import load_dotenv #.env files
from pathlib import Path #.env files
import os
env_path = Path(os.path.expanduser('PATH/HERE/.env'))
load_dotenv(dotenv_path=env_path)
for a in range(number_of_tcHATs):
     hat_list.append([])
     hat_list[a]=daqhats.mcc134(a)
     for x in range(int(os.getenv('NUMBER_OF_THERMOCOUPLES'))):
         hat_list[a].tc_type_write(x,daqhats.TcTypes.TYPE_N)

The updated code I'm using is (only the last line changes):

from dotenv import load_dotenv #.env files
from pathlib import Path #.env files
import os
env_path = Path(os.path.expanduser('PATH/HERE/.env'))
load_dotenv(dotenv_path=env_path)
for a in range(number_of_tcHATs):
    hat_list.append([])
    hat_list[a]=daqhats.mcc134(a)
    for x in range(int(os.getenv('NUMBER_OF_THERMOCOUPLES'))):
        print("hat_list[" + str(a) + "].tc_type_write(" + str(x) + ",daqhats.TcTypes."+ os.getenv('THERMOCOUPLE_TYPE') +")")

The pull from the .env and concatenation works as I get the following on screen:

hat_list[0].tc_type_write(0,daqhats.TcTypes.TYPE_N)
hat_list[0].tc_type_write(1,daqhats.TcTypes.TYPE_N)
hat_list[0].tc_type_write(2,daqhats.TcTypes.TYPE_N)
hat_list[0].tc_type_write(3,daqhats.TcTypes.TYPE_N)
hat_list[1].tc_type_write(0,daqhats.TcTypes.TYPE_N)
hat_list[1].tc_type_write(1,daqhats.TcTypes.TYPE_N)
hat_list[1].tc_type_write(2,daqhats.TcTypes.TYPE_N)
hat_list[1].tc_type_write(3,daqhats.TcTypes.TYPE_N)

But it never runs the code itself. How can I achieve this?

Read my comments again, according to getting started you are missing the load_dotenv() call. Just importing it is not enough, you need to call it. Without that, os.getenv() will only return variables from OS environment and as such is not aware of any .env files.

from dotenv import load_dotenv

load_dotenv()  # take environment variables from .env.

# Code of your application, which uses environment variables (e.g. from `os.environ` or
# `os.getenv`) as if they came from the actual environment.

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