Running a Python script from PHP

Posted on

Solving problem is about exposing yourself to as many situations as possible like Running a Python script from PHP and practice these strategies over and over. With time, it becomes second nature and a natural way you approach any problems in general. Big or small, always start with a plan, use other strategies mentioned here till you are confident and ready to code the solution.
In this post, my aim is to share an overview the topic about Running a Python script from PHP, which can be followed any time. Take easy to follow this discuss.

Running a Python script from PHP

I’m trying to run a Python script from PHP using the following command:

exec('/usr/bin/python2.7 /srv/http/assets/py/ arg1 arg2');

However, PHP simply doesn’t produce any output. Error reporting is set to E_ALL and display_errors is on.

Here’s what I’ve tried:

  • I used python2, /usr/bin/python2 and python2.7 instead of /usr/bin/python2.7
  • I also used a relative path instead of an absolute path which didn’t change anything either.
  • I tried using the commands exec, shell_exec, system.

However, if I run

if (exec('echo TEST') == 'TEST')
    echo 'exec works!';

it works perfectly fine while shutdown now doesn’t do anything.

PHP has the permissions to access and execute the file.

EDIT: Thanks to Alejandro, I was able to fix the problem. If you have the same problem, don’t forget that your webserver probably/hopefully doesn’t run as root. Try logging in as your webserver’s user or a user with similar permissions and try to run the commands yourself.

Answer #1:

Tested on Ubuntu Server 10.04. I hope it helps you also on Arch Linux.

In PHP use shell_exec function:

Execute command via shell and return the complete output as a string.

It returns the output from the executed command or NULL if an error
occurred or the command produces no output.

$command = escapeshellcmd('/usr/custom/');
$output = shell_exec($command);
echo $output;

In Python file, verify this text in first line: (see shebang explain):

#!/usr/bin/env python

Also Python file must have correct privileges (execution for user www-data / apache if PHP script runs in browser or curl)
and/or must be “executable”. Also all commands into .py file must have correct privileges:

Taken from php manual:

Just a quick reminder for those trying to use shell_exec on a
unix-type platform and can’t seem to get it to work. PHP executes as
the web user on the system (generally www for Apache), so you need to
make sure that the web user has rights to whatever files or
directories that you are trying to use in the shell_exec command.
Other wise, it won’t appear to be doing anything.

To make executable a file on unix-type platforms:

chmod +x
Answered By: Alejandro Quiroz

Answer #2:

I recommend using passthru and handling the output buffer directly:

passthru('/usr/bin/python2.7 /srv/http/assets/py/ arg1 arg2');
$output = ob_get_clean();
Answered By: Niklas Lindblad

Answer #3:

If you want to know the return status of the command and get the entire stdout output you can actually use exec:

$command = 'ls';
exec($command, $out, $status);

$out is an array of all lines. $status is the return status. Very useful for debugging.

If you also want to see the stderr output you can either play with proc_open or simply add 2>&1 to your $command. The latter is often sufficient to get things working and way faster to “implement”.

Answered By: kqw

Answer #4:

Alejandro nailed it, adding clarification to the exception (Ubuntu or Debian) – I don’t have the rep to add to the answer itself:

sudoers file:
sudo visudo

exception added:

Answered By: Colin Miles

Answer #5:

To clarify which command to use based on the situation

exec() – Execute an external program

system() – Execute an external program and display the output

passthru() – Execute an external program and display raw output


Answered By: Agnel Vishal

Answer #6:

In my case I needed to create a new folder in the www directory called scripts. Within scripts I added a new file called

I then used sudo chown www-data:root scripts and sudo chown www-data:root

Then I went to the new scripts directory and used sudo chmod +x

My file it looks like this. Note the different Python version:

#!/usr/bin/env python3.5
print("Hello World!")

From php I now do this:

$message = exec("/var/www/scripts/ 2>&1");

And you should see: Hello World!

Answered By: Tim Hallman

Answer #7:

The above methods seem to be complex. Use my method as a reference.

I have these two files:

  • run.php


Here, I’ve created an HTML page which contains a GO button. Whenever you press this button a new folder will be created in directory whose path you have mentioned.


   <form method="post">
    <input type="submit" value="GO" name="GO">
		shell_exec("python /var/www/html/lab/");

#!/usr/bin/env python    
import os
Answered By: SMshrimant

Answer #8:

This is so trivial, but just wanted to help anyone who already followed along Alejandro’s suggestion but encountered this error:

sh: command not found

If anyone encountered that error, then a little change needs to be made to the php file by Alejandro:

$command = escapeshellcmd('python');
Answered By: Gerald Joshua

Leave a Reply

Your email address will not be published.