Use environment variable in python command

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

I’m having problem with one section of code where an environment variable is used as part of a line of code (apologies if this isn’t the right terminology).

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 population of information from the .env file and the 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)

Now how do I change the last line of my code to get it to execute that line of code, rather than just print it to the screen?

Hello, @ocbbt , welcome to Python! Let me see if I can help.

One obvious difference between the last line of your old code and the same line of the new code is that what was an executable statement is now an expression to print: hat_list[a].… became print("hat_list[" + str(a) + "].… So, undo that change.

But maybe what you really want to know is how to go from:

daqhats.TcTypes.TYPE_N

where the TYPE_N name is hardcoded, to

daqhats.TcTypes. (…magic happens…) os.getenv('THERMOCOUPLE_TYPE')

where the name is taken from the environment variable THERMOCOUPLE_TYPE.

In daqhats.TcTypes.TYPE_N, the period “.” indicates “retrieve an attribute from the thing to my left, using the thing to my right as the attribute name”. Python sets this up when it parses the module’s source code. You instead want Python to set this up when it runs the code.

The answer getattr(). You pass it an object, and a string naming an attribute of the object. It gives you the value of that attribute in that object. You can use it like this:

tc_type = getattr(daqhats.TcTypes, os.getenv('THERMOCOUPLE_TYPE'))
hat_list[a].tc_type_write(x,tc_type)

Does that make sense?

P.S. it sometimes helps to call an object’s special __getattr__() function. This lets you write the code in-line. Sometimes that works better. (Though, in this case, I think it results in a line which is too long for good readability.)

hat_list[a].tc_type_write(x,daqhats.TcTypes.__getattr__(os.getenv('THERMOCOUPLE_TYPE')))
2 Likes

Hi Jim,

Thanks for the reply. I think you should write python tutorials because every sentence made absolute sense! Which, when reading most of the tutorials or manuals, rarely happens for me!

I’ll give it a go! :+1: :ok_hand:

1 Like

Thought for completeness I would report back…it works perfectly.

Looking through my previous code I had tried something like that in the past, but didn’t know about the getattr function, just tried to place a variable into the command string instead. So close!

One minor typo in your line of code (for anyone using it in the future), you’re missing a closing bracket.

Once again, thanks Jim.

2 Likes

I am glad it was helpful.

Thank you for pointing out the missing right parenthesis in the last line of my earlier message. I have edited that code with a correction.

1 Like

During my travels today I bumped into this, and thought it might help future visitors: