Run shell command from php,

I need to run a python program with a command line argument from my PHP script

This is my code

<?php


$output=shell_exec('python /path/to/python_from_php.py input1 input2');

echo $output;
?>

      

I am getting content inside shell_exec function as output. I have tried using only

$output=exec('python /path/to/python_from_php.py input1 input2');

      

I only get the second input as my output. But I want to be able to print the content of the input through my python script. If I remove the "echo $ output" line, I get no output. My python code

import sys
a=(sys.argv)
for i in (sys.argv):
 print i

      

+3


source to share


3 answers


this code gives you the output from the shell

 <?php
   $output = shell_exec('ls -lart');
   echo "<pre>$output</pre>";
 ?>

      



from this help php also makes sure php is not running in safe mode but you can try to just call the python script from php

 <?php
    $my_command = escapeshellcmd('python path/to/python_file.py');
    $command_output = shell_exec($my_command);
    echo $command_output;
 ?>

      

0


source


How the OP wants:

But I want to be able to print the content of the input through my python script. If I remove the line "echo $ output", I am not getting any result.

should be used passthru

, description



<?php

passthru('python /path/to/python_from_php.py input1 input2');

?>

      

Check that the php user has access to run python and your python script.

Live demo here

0


source


One option is to use passthru (), but if you don't want to manipulate the output buffer and you want the output in an array, you can add an output parameter to the exec command like so:

<?php

error_reporting(E_ALL);

$command = escapeshellcmd('/usr/bin/python /path/to/python_from_php.py arg1 arg2');

exec($command, $output);

for ($l=0; $l < count($output); ++$l) {
    echo $output[$l]."\n";
};

      

0


source







All Articles