Could not run python script using PHP

443 Views Asked by At

I could obtain the output (in text file) of a python file by executing it on the command line, but was not able to obtain the output (in text file) by executing it using php exec(). What did i do wrongly?

this is my python file (example.py):

inputfile = open("input.txt",r)
data = inputfile.read()
inputfile.close()

outputfile = open("output.txt","w")
outputfile.write(str(data))
outputfile.write(str(data))
outputfile.close()

this is my php file (example2.php):

<?php 
$string = "hello";
file_put_contents('input.txt', $string);
exec('python example.py');
$result = file_get_contents('output.txt');

i typed this on the commandline and it worked:

python example.py
1

There are 1 best solutions below

0
On

The problem is solved by executing a bat file in php to run the python script.

exec('cmd /c ./path/run_example.bat')

this is the bat file i wrote:

cd C:\Users\Username\AppData\Local\Programs\Python\Python36 # very important if you are runnning it on a server.
python --version # make sure the version is the same as what you expected
python C:\path\example.py