How can run python on php? [duplicate]


December 2018


234 time


This question already has an answer here:

I made a data input web page with a form. And i want to run a python script on the server using the values from the web page and create an output file on the server. Now I can input data and submit the web page. But then python script is not creating the output file on the server.

Below are my scripts.

First, I connect to index.php and input some text on the form and submit it

Below is index.php


<form action="1test.php" method="get">
<input type="text" name="name" />
<input type="submit" />


Secondly, 1test.php executes using the form value on index.php.

Below is 1test.php

$name = $_GET['name'];
$cmd = "python " . $name;
echo $cmd;

my script work before python script. I can see $cmd value on web. But php can't execute python. python script has execute permission. Lastly, the python script makes the file on the server. Form values will be array data on python.

Below is

import sys
sip = sys.argv[1]
with open("doc.txt",'w') as f:

1 answers


Try to redirect errors from stderr to stdin with 2>&1 and capture the exit code:


$name = $_GET['name'];
$cmd = escapeshellcmd("python $name 2>&1");

echo "$cmd" . PHP_EOL;

exec($cmd, $output, $return_var);

echo "$return_var:" . PHP_EOL;

The $output is an array of lines. If the script returns 0 (value of $return_var), it means success.