Harry Campbell
Harry Campbell

Reputation: 39

How to make a Python interpreter for a webpage

There might already be questions like this, but none of them answer my question. I have a script that loads a Python script in the directory and then displays a output with PHP:

<?php

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

$command = "scripts/sg.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'>

</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 is the Python code it should run, that is located in the directory:

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

print "Initializing Python Script"

secret = 1337
guess = 0
count = 0
#Help the user give number range.
print 'Guess s number it`s between 0 <-> 2000 '
while guess != secret:
guess = input("Guess: ")
if guess < secret:
    print "to small"
elif guess > secret:
    print "to big"        
count += 1
print 'You guessed the number in %s try' % count

The Python actually works! However it seems that Python's inputs don't work, they create a EOF error (end of file error).

Can anybody help me and suggest a way to create a Python interpreter that runs the Python file found in the directory. Just like, skuplt.org, but instead of running code a client users, it runs a Python file located in a directory, like stated above.

Upvotes: 2

Views: 1363

Answers (1)

Hugh Bothwell
Hugh Bothwell

Reputation: 56674

popen opens a pipe that is one-way only; you can read from it or write to it, but not both.

You want to use proc_open instead - see http://php.net/manual/en/function.proc-open.php

Upvotes: 3

Related Questions