Run a Python script from PHP
Solvedjordane45 Posted messages 30426 Registration date Status Moderator Last intervention -
Hello,
I launched WampServer and created a folder that contains a .php file and a hello.py file. The problem is that no matter what I try, nothing works. It is important to note that I prefer to avoid requests since both programs are supposed to be server-side. Here is what I tried:
<?php $python_script = "hello.py"; $output = shell_exec("python" . $python_script); echo "<h1>Output:{$output}</h1>"; ?> My Python file looks like this:
import sys #to retrieve argv later print("Hello") I tried with exec() or even escapeshellcmd() which I then insert into shell_exec() but without success. With a var_dump() I get path-filename-php php:line-number:string '' (length=0)".
Would someone know where the problem might come from?
3 answers
-
Hello
First, there is missing a space after the word python in your command line.
Next, I think you should provide the full path to the python executable, otherwise it may not be able to locate its location to run it
.
Best regards,
Jordane -
Hello,
Thank you for replying. I have made the changes but nothing displays after the word "output" on the page. Here is the corrected version:
<?php $python_script = "C:/wamp64/www/php_py/hello.py"; $output = shell_exec("python " . $python_script); echo "<h1>Output: {$output} </h1>"; ?>I tried with \\ or just \ but the result is the same. However, trying on cmd launches the Python program.
Edit: I tried on Ubuntu instead of Windows and it works. The problem doesn’t seem to come from the PHP code.
-
I found the solution, even though Python was in my PATH, it didn’t work in PHP and the php.ini configuration in WampServer had no field specifying that functions were disabled; the only somewhat primitive but functional solution is to do:
<?php $output = shell_exec("C:\chemin-vers-python\Python3xx\python.exe hello.py"); echo "<h1>Output:" . $output . "</h1>"; ?>