3

I need to run a python program with 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 the contents inside shell_exec function as the output. I tried using only

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

I am getting only the second input as my output. But what I want is I should be able to print the input contents through my python script. If I remove the "echo $output" line I am not getting any output. My python code

import sys
a=(sys.argv)
for i in (sys.argv):
 print i
halfpastfour.am
  • 5,764
  • 3
  • 44
  • 61
Niranjan Dattatreya
  • 405
  • 1
  • 6
  • 18

3 Answers3

1

this code gives you the output from shell

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

from this reference php also ensure php is not running in safe mode but you could try 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;
 ?>
Zuko
  • 2,764
  • 30
  • 30
0

As OP wants to:

But what I want is I should be able to print the input contents through my python script. If I remove the "echo $output" line I am not getting any output.

should be used passthru, description

<?php

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

?>

Check, that you php user have access to run python and your python script.

Live demo is here

Reishin
  • 1,854
  • 18
  • 21
0

One option is to use passthru(), but if you don't want to manage the output buffer, and having the output in an array is desirable, you can add an output parameter to the exec command as 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";
};
Alex Forbes
  • 3,039
  • 2
  • 19
  • 22