I have a script in tasks that runs perfectly fine when I am not using environment variables. It runs in bash console fine and runs in tasks.
I have now added environment variables via bash console like below...
export TwilioAccountSID=MYACCOUNTID
These have added fine, and I can see them when running env inside of the bash console. The code runs fine in bash and executes perfectly.
They are within the script like this...
TwilioAccountSID = os.environ.get("TwilioAccountID")
The problem I have is when I now setup a task for this script, it throws a KeyError.
Within the tasks command line I have added the environment variables like this...
export TwilioAccountSID=MYACCOUNTID; python3 myscript.py
I get a KeyError when doing this, and when just running:
python3 myscript.py
Can anyone help me to understand how to make this work?
I followed this from another thread...
https://help.pythonanywhere.com/pages/environment-variables-for-web-apps/
I don't fully understand that article (new to Python), but attempted to follow it.
I have setup a .env file in the same directory as my script. Added my environment variables in there. I have then installed the dotenv library via bash console, and imported the load object.
I also added this to my script...
from dotenv import load_dotenv
project_folder = os.path.expanduser('mydirectory') # adjust as appropriate
load_dotenv(os.path.join(project_folder, '.env'))
But now I do not know what to do to get this to work in tasks?
Any help is much appreciated.
As a side note, I did add this line to the command in the task scheduler like so:
set -a; source ~/.env; set +a python3 myscript.py
And this has run successfully as per the logs, but the code hasn't executed. No SMS's were sent.
I am now completely stuck as to what to do next? Any help or direction on what I am doing wrong is much appreciated.