My python script isn’t executed by PHP shell_exec()

I already seen issue talking about this on the platform but it didn’t resolve my problem.

I want to execute this python script :

import mysql.connector
import smtplib, ssl
from email.message import EmailMessage

def get_last_temperature():
    username = '***'
    passwd = '***'
    host = '127.0.0.1'
    db = 'temperature'
    sql_query = "SELECT * FROM temperature ORDER BY ID DESC LIMIT 1;"
    temp = 0

    # Connecto to database temperature
    conn = mysql.connector.connect(user=username, password=passwd, host=host, database=db)

    # execute sql query
    cursor = conn.cursor(dictionary=True)
    cursor.execute(sql_query)

    # get response
    result = cursor.fetchall()
    conn.close()
    size = len(result)

    temp = result[0]['temperature']

    return temp

def send_temperature(temp):
    subject = 'Temperature anomaly'
    body = 'Last temperature record is out of range : {}'.format(temp)
    sender = '***'
    receiver = "***"
    passwd = "***"

    msg = EmailMessage()
    msg['From'] = sender
    msg['To'] = receiver
    msg['Subject'] = subject
    msg.set_content(body)

    context = ssl.create_default_context()

    with smtplib.SMTP_SSL('smtp.gmail.com', 465, context=context) as server:
        server.login(sender, passwd)
        server.sendmail(sender, receiver, msg.as_string())

if __name__ == '__main__':
    try:
        print(ssl.OPENSSL_VERSION)
        temp = get_last_temperature()
        send_temperature(temp)
        print("Temperature sent by email.")
    except:
        print("Error")

From this PHP script :

if ($temperature < 7 || $temperature > 40)
{
    // $command = escapeshellcmd('touch /tmp/test.txt');
    // putenv('PYTHONPATH=/home/user/.local/lib/python3.8/site-packages/');
    $output = shell_exec('/usr/bin/python3 /home/user/Documents/Projet/send_temp/anomaly/main.py');
    echo "anomaly output : " . $output;
}

When i execute the python script manually it works.
I added www-data as the user of the python script and it doesn’t work.
As you can see i tried with simple command such as ‘touch /tmp/test.txt’ and it works.
Also when i execute a simple python script which create a tmp file it also work.

But with my script it doesn’t work. I also tried to add a different environment because it already solved some problems i had with mysql but it doesn’t work too and i don’t have any output.

I guess the problem is related to mysql or smtplib but i can’t find.

Can anyone give me some help ? 😉