Python Cannot Import OpenAI Library When Called via PHP

I’m having trouble with my Python script that uses the OpenAI library. When I run the script directly from the command line on my Raspberry Pi, everything works perfectly. But when I try to execute the same Python script through PHP using shell_exec, I get this error:

Traceback (most recent call last):
  File "/var/www/html/ai-assistant.py", line 18, in <module>
    import openai
ModuleNotFoundError: No module named 'openai'

The weird thing is that other Python modules work fine when called from PHP, just not the OpenAI one. I think this might be related to different Python environments or maybe a PATH issue between running scripts manually versus through the web server. Has anyone dealt with this before? What’s the best way to make sure PHP can access the same Python modules that work in the terminal?

This is definitely a virtual environment issue. The web server user (usually www-data) can’t access your Python virtual environment where OpenAI is installed. I hit this exact problem on my Ubuntu server last month. Quick fix: use the full path to your virtual environment’s Python interpreter in your PHP shell_exec call instead of just ‘python’. Try /home/youruser/venv/bin/python /var/www/html/ai-assistant.py instead of python /var/www/html/ai-assistant.py. You could also install OpenAI globally with sudo pip install openai, but that’s not great for security. The full path approach worked perfectly for me and keeps everything properly isolated.

Had the same headache with my Flask app deployment. PHP runs under a different user with its own environment variables. When you pip installed OpenAI, it went to your user’s Python site-packages, but the web server can’t see that location. Besides the virtual environment fix mentioned above, you can explicitly set PYTHONPATH in your PHP script before calling shell_exec. Try putenv('PYTHONPATH=/home/youruser/.local/lib/python3.x/site-packages'); then your shell_exec call. This tells Python exactly where to find modules. I like this better than hardcoding interpreter paths, especially with multiple Python versions on the same system.