-1

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
stephanie
  • 1
  • 1
  • Try to use absolute paths. – Klaus D. Jul 03 '17 at 07:07
  • Perhaps [this answer](https://stackoverflow.com/questions/19735250/running-a-python-script-from-php) can help – Kyrre Jul 03 '17 at 07:08
  • use `shell_exec()`.. Here is answer: [running-python-script-in-php-capture-all-outputs](https://stackoverflow.com/questions/37042904/running-python-script-in-php-capture-all-outputs/37042910#37042910) – Murad Hasan Jul 03 '17 at 07:09
  • @KlausD. Thanks for the advice. It helped partially. The solution will be posted. below. – stephanie Jul 03 '17 at 09:39

1 Answers1

0

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
stephanie
  • 1
  • 1