Getting PHP to run a Python script

I am trying to run a Python program using PHP. Here’s the code

$command = '/usr/local/bin/python script.py file';
$temp = exec($command, $output);

This works through the command line but not while running it through the browser. I am using Apache so probably it needs the right privileges? I am pretty new to Linux and have no idea how to get this working.

Any help would be appreciated!

Edit 1:

Tried to use proc_open but nothing happens. I gave the full path to the script. Made the script executable but no luck. Any other things I can try on the server? (It’s a CentOS 5)

Here is Solutions:

We have many solutions to this problem, But we recommend you to use the first solution because it is tested & true solution that will 100% work for you.

Solution 1

You need to pass the full path to the script and you also need to make sure that the script is readable by the user running the web server (which means every directory in the path must be +x to the web user).

Solution 2

Realized what was wrong:

  1. The domain was set up as a virtual host and PHP’s safe_mode was enabled. proc_open, exec, system, passthru etc. do not work under safe_mode I guess.

  2. Put the script in the directory accessible by the vhost. Apache wasn’t able to access the directories outside the vhost document root.

Thanks for the help!

Solution 3

Few checkpoints

  • script.py should be pass full path, eg, /home/abhinav/script.py
  • script.py should be executable, chmod +x script.py

Solution 4

To get my CodeIgniter helper to run a python script, I had to put #!/usr/bin/python on the first line of my python script, and NOT call python from the exec.

+1 for also doing chmod +x

My helper looks like this:

<?php
    function scrape($site, $key, $user_id)
    {
        $cmd = str_replace('system/','',BASEPATH).APPPATH."python/spider.py -u $site -k $key -i $user_id";
        $resp = exec($cmd, $out);
        return $out;
    }
?>

Note: Use and implement solution 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply