I figured out the problem. as I mentioned in a couple of the comments, I am using a python virtual environment. When I was executing the python script from the command line, the python interpreter from within the python virtual environment was being used, and everything was fine. Whenever I executed the script rom
shell_exec, the default installation of the python interpreter was being used, and this was where the error occurred.
I am not very experienced in using python virtual environments, so that is likely why it took so long for me to arrive at an understanding of the problem. Luckily, MohammedAyoubBENJELLOUN's comment about shell_exec using the default python installation put me on the right path, and I figured it out from there.
To solve this problem, I simply invoked the python interpreter at the path of the interpreter inside of the python virtual environment instead of trying to activate the virtual environment and then executing.
For example, I used:
. activate keras && python test_script.py