88

I have a Python script I recently wrote that I call using the command line with some options. I now want a very thin web interface to call this script locally on my Mac.

I don't want to go through the minor trouble of installing mod_python or mod_wsgi on my Mac, so I was just going to do a system() or popen() from PHP to call the Python script.

Any better ideas?

10 Answers 10

113

Depending on what you are doing, system() or popen() may be perfect. Use system() if the Python script has no output, or if you want the Python script's output to go directly to the browser. Use popen() if you want to write data to the Python script's standard input, or read data from the Python script's standard output in php. popen() will only let you read or write, but not both. If you want both, check out proc_open(), but with two way communication between programs you need to be careful to avoid deadlocks, where each program is waiting for the other to do something.

If you want to pass user supplied data to the Python script, then the big thing to be careful about is command injection. If you aren't careful, your user could send you data like "; evilcommand ;" and make your program execute arbitrary commands against your will.

escapeshellarg() and escapeshellcmd() can help with this, but personally I like to remove everything that isn't a known good character, using something like

preg_replace('/[^a-zA-Z0-9]/', '', $str)
4
  • 1
    The subprocess module has replaced using os.Popen[n] directly. You should use that instead. Commented Oct 4, 2008 at 15:57
  • 6
    @Nick Stinemates: We are talking about PHP functions ;)
    – Glaslos
    Commented Dec 6, 2011 at 5:54
  • is there no solutions that does NOT involve a shell, like C's execve() except that it runs on a separate process instead of having to fork() first.
    – Lie Ryan
    Commented Jul 22, 2012 at 15:57
  • There is and there's always been solutions but you must run python somewhere to get something out of it. You could make simple python service that just waits for input until it has some or you could trigger you program somehow (linux inotify for example), then there's those PHP extensions and then there is local sockets for linux servers. Python in PHP looks like best NoShell solution as other (non-plugin) would always have some kind of shell around your python. Commented Dec 16, 2014 at 21:58
30

The shell_exec() operator will also allow you to run python scripts using similar syntax to above

In a python file called python.py:

hello = "hello"
world = "world"
print hello + " " + world

In a php file called python.php:

$python = shell_exec(python python.py);
echo $python;
0
14

You can run a python script via php, and outputs on browser.

Basically you have to call the python script this way:

$command = "python /path/to/python_script.py 2>&1";
$pid = popen( $command,"r");
while( !feof( $pid ) )
{
 echo fread($pid, 256);
 flush();
 ob_flush();
 usleep(100000);
}
pclose($pid);

Note: if you run any time.sleep() in you python code, it will not outputs the results on browser.

For full codes working, visit How to execute python script from php and show output on browser

2
  • How to specify the path here relative and absolute. Basically I have my python script present under lets say folder tempmon and the same folder contains my python script. I want the application to be portable so can just copy the tempmon folder under htdocs. And the same should work on different machines.
    – krishna
    Commented Jun 17, 2015 at 17:40
  • Perfectly worked. You can add opening and closing php tags <?php ?> for better understanding for beginner
    – Zaheer
    Commented Oct 10, 2017 at 18:44
7

I do this kind of thing all the time for quick-and-dirty scripts. It's quite common to have a CGI or PHP script that just uses system/popen to call some external program.

Just be extra careful if your web server is open to the internet at large. Be sure to sanitize your GET/POST input in this case so as to not allow attackers to run arbitrary commands on your machine.

3

Your call_python_file.php should look like this:

<?php
    $item='Everything is awesome!!';
    $tmp = exec("py.py $item");
    echo $tmp;
?>

This executes the python script and outputs the result to the browser. While in your python script the (sys.argv[1:]) variable will bring in all your arguments. To display the argv as a string for wherever your php is pulling from so if you want to do a text area:

import sys

list1 = ' '.join(sys.argv[1:])

def main():
  print list1

if __name__ == '__main__':
    main()
1

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

I have this two files

run.php

mkdir.py

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

run.php

<html>
 <body>
  <head>
   <title>
     run
   </title>
  </head>

   <form method="post">

    <input type="submit" value="GO" name="GO">
   </form>
 </body>
</html>

<?php
    if(isset($_POST['GO']))
    {
        shell_exec("python /var/www/html/lab/mkdir.py");
        echo"success";
    }
?>

mkdir.py

#!/usr/bin/env python    
import os    
os.makedirs("thisfolder");
0

Note that if you are using a virtual environment (as in shared hosting) then you must adjust your path to python, e.g: /home/user/mypython/bin/python ./cgi-bin/test.py

0

is so easy 😁 You can use [phpy - library for php][1] php file

<?php
  require_once "vendor/autoload.php";

  use app\core\App;

  $app = new App();
  $python = $app->python;
  $output = $python->set(your python path)->send(data..)->gen();
  var_dump($ouput);

python file:

import include.library.phpy as phpy
print(phpy.get_data(number of data , first = 1 , two =2 ...))

you can see also example in github page [1]: https://github.com/Raeen123/phpy

0

I agree, all the other options are great. I will not detail them. But, we also have a few others. First, you can try OpenAI and a fuzzy logic solution. Also, there are a few GitHub projects that can help. And Finally, there are string search and replace converters.

The last two options, are found on my website for free. Both too and from PHP<->Python are covered, and we offer multiple converters for each.

https://properprogramming.com/tools/converters/online-php-to-python-3-converter-version-2/ https://properprogramming.com/tools/converters/free-online-php-to-python-3-converter/

Hope these help.

-3

If you want to execute your Python script in PHP, it's necessary to do this command in your php script:

exec('your script python.py')
1
  • 1
    a) Spaces separate parameters, i.e. this tries to call the program your with the parameters script and python.py. b) Unless the Python script has a proper shebang one has to call the Python interpreter and pass the script name to it (python script.py). Even with a proper shebang this is wrong as you would then call ./script.py instead of using the interpreter name.
    – Tox
    Commented Aug 14, 2019 at 13:08

Not the answer you're looking for? Browse other questions tagged or ask your own question.