how to run a python file using exec() function in php

one text

Solution:

First you need to make your python file CLI compatible. You need to catch the arguments. The easiest way to do it would be something like this:

import sys

def myFunc(user, pwd):
    print(user,pwd)

if __name__ == '__main__':
    
    if len(sys.argv) >= 3:
        user = sys.argv[1]
        pwd = sys.argv[2]
        myFunc(user, pwd)

Also have a look at argparse and click.

Then you can call the script from PHP and provide the credentials. There are actually several ways to do it. While your wish exec will not return the output of the python script

passthru

$output = passthru("python3 myScript.py $user $pwd");

shell_exec

$prog = 'python3 myScript.py '.$user.' '.$pwd;
$output = shell_exec($prog);

exec

exec("python3 myScript.py $user $pwd");  

Source