-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
4
  • Try to use absolute paths. Commented Jul 3, 2017 at 7:07
  • Perhaps this answer can help Commented Jul 3, 2017 at 7:08
  • use shell_exec().. Here is answer: running-python-script-in-php-capture-all-outputs Commented Jul 3, 2017 at 7:09
  • @KlausD. Thanks for the advice. It helped partially. The solution will be posted. below. Commented Jul 3, 2017 at 9:39

1 Answer 1

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.