0

this is my first post so, please Please be lenient :)

With reference at the subject, before writing I have really done a thorough research on stack overflow and the answer closest I could find was Passing value from PHP script to Python script.

In my test I've this situation: prova.php file:

<?php
$item1 = 3;
$item2 = 4;
$tmp = exec("python ../cgi-bin/test.py $item1 $item2"); 
echo $tmp; // invia la richiesta a Python
?>

Then in the Python test.py file I wrote:

#!/usr/local/bin/python     
import sys              
print sys.argv[1] , sys.argv[2] 

All this works fine and the page prova.php shows the values โ€‹โ€‹of the variables, ie 3 and 4

What I can't understand is how to proceed in test.py to make e.g. product sys.argv[1] * sys.argv[2] and return it to PHP. All attempts I made show "prova.php" as a blank page. Thanks in advance for your attention.

==================================================================== WOW, Dear Georg, Matt, Andrew and Jarek, Thank you so much for your valuable advice! In a few minutes you have solved a problem that I was analyzing from hours (as you may have guessed I'm a beginner).

Now everything works perfectly!

If possible, I would like to know one more thing: is there a way that when python runs the line "print ..." (to return the result in $output), the value is not displayed on the page prova.php, but only stored in $output?

Thanks again!

Community
  • 1
  • 1
indirizzo
  • 1
  • 1
  • In python, you convert both args to integers, multiply and print the result: `print int(sys.argv[1])*int(sys.argv[2])` โ€“ georg Nov 21 '14 at 13:20

3 Answers3

0

you have to pass a variable that will receive output by reference to exec:

<?php $item1 = 3;
$item2 = 4; 
exec("python ../cgi-bin/test.py $item1 $item2", $output);  
echo $output; // invia la richiesta a Python ?>
glglgl
  • 89,107
  • 13
  • 149
  • 217
Jarek.D
  • 1,274
  • 1
  • 8
  • 18
0

Pass a second parameter to the exec command to capture the output from the child process (python). http://php.net/manual/en/function.exec.php

$output = array() exec("python...",$output) echo $output[0]

Matt O
  • 1,336
  • 2
  • 10
  • 19
0

In a world of micro services it would be best to offer a REST interface and get the data from a CuRL call. Certainly, this is an architecture call but you're most likely better suited to take this approach. If it's not possible to take this approach, use the exec command as others have noted. However, if your python is isolated in a virtualenv you will need to supply the full python path and full python script location.

<?php 
    $item1 = 3;
    $item2 = 4; 
    exec("/path/to/python-venv/bin/python /path/to/python-venv/src/cgi-bin/test.py $item1     $item2", $result);  
    echo $result;
?>

#!/usr/bin/env python     
import sys
print int(sys.argv[1]) * int(sys.argv[2])
Andrew Sledge
  • 10,163
  • 2
  • 29
  • 30