Run a Python program from PHP


In PHP, the ‘shell_exec’ function can be used. It can be executed via the shell and the result can be returned as a string. It returns an error if NULL is passed from the command line or returns no output at all.

Below is a code demonstration of the same −

<?php
   $command_exec = escapeshellcmd('path-to-.py-file');
   $str_output = shell_exec($command_exec);
   echo $str_output;
?>

The right privileges need to be given so that the python script is successfully executed.

Note − While working on a Unix type of platform, PHP code is executed as a web user. Hence, the web user should be given the necessary rights to the directories and sub-directories.

Updated on: 06-Apr-2020

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements