How to execute python script from php and show output on browser

In this post I will show you how to execute a python script via php, and show the terminal output, in real time, on the browser.

You’ll be able to pass parameters from php to python.

First of all, to show the output on the browser, is realtime, you will need that PHP running in server module mode, not on CGI.

To check it, just run php_info().

We will use basically popen php function ( to do it.

The code:


$param1 = "first";
$param2 = "second";
$param3 = "third";

$command = "python /home/wellington/";
$command .= " $param1 $param2 $param3 2>&1";

header('Content-Type: text/html; charset=utf-8');
echo '<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />';
echo "<style type='text/css'>
 color: #7FFF00;
 font-family:'Lucida Console',sans-serif !important;
 font-size: 12px;

$pid = popen( $command,"r");

echo "<body><pre>";
while( !feof( $pid ) )
 echo fread($pid, 256);
 echo "<script>window.scrollTo(0,99999);</script>";

echo "</pre><script>window.scrollTo(0,99999);</script>";
echo "<br /><br />Script finalizado<br /><br />";

And now, the Python script:

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Script Python Example
import time
import sys

print "Initializing Python Script"

print "The passed arguments are ", sys.argv

print "Writing lines to a file"

ifile = open( "/tmp/testfile", "w+")
for i in range(0,100):
 ifile.write( "One of the lines of the filen" )
 print "Printing line ",i," to /tmp/testfile"


print "Reading and printing lines of /tmp/testfile"
ifile = open( "/tmp/testfile", "r")
for line in ifile:
 print line
print "End of Python Script"


  1. Mostafa
    Sooo thanks for this great , useful , nice code ;)

Trackbacks / Pings

Deixe uma resposta

O seu endereço de email não será publicado Campos obrigatórios são marcados *


Você pode usar estas tags e atributos de HTML: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>