php

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 (http://br.php.net/manual/pt_BR/function.popen.php) to do it.

The code:


<?php

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

$command = "python /home/wellington/python_script_example.py";
$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'>
 body{
 background:#000;
 color: #7FFF00;
 font-family:'Lucida Console',sans-serif !important;
 font-size: 12px;
 }
 </style>";

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

echo "<body><pre>";
while( !feof( $pid ) )
{
 echo fread($pid, 256);
 flush();
 ob_flush();
 echo "<script>window.scrollTo(0,99999);</script>";
 usleep(100000);
}
pclose($pid);

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"

ifile.close()

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

2 Comments

  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>