How to call Python file from within PHP?


To call a Python file from within a PHP file, you need to call it using the shell_exec function.

For example

<?php
    $command = escapeshellcmd('/usr/custom/test.py');
    $output = shell_exec($command);
    echo $output;
?>

This will call the script. But in your script at the top, you'll need to specify the interpreter as well. So in your py file, add the following line at the top:

#!/usr/bin/env python

Alternatively you can also provide the interpreter when executing the command.

For example

<?php
    $command = escapeshellcmd('python3 /usr/custom/test.py');
    $output = shell_exec($command);
    echo $output;
?>

Updated on: 13-Dec-2019

8K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements