1

I am trying to call a python script from php. However, I cannot figure out how to return the result to my php script in order to use it there. My php script is as follows:

<?php
  $input = 'help';
  $output = passthru("/usr/bin/python3.5 /path/test.py '$input'");
  echo $output;
?>

whilst my python script 'test.py' is:

import sys
json2 = sys.argv[1]
Stphane
  • 3,368
  • 5
  • 32
  • 47
Christian
  • 991
  • 2
  • 13
  • 25

1 Answers1

2

That's because your python script returns nothing. Just doing:

json2 = sys.argv[1]

Only assigns the value to json2. I suspect you're trying to do something like:

import sys
json2 = sys.argv[1]
print json2

That seems to work just fine:

~ # php -a             
Interactive shell

php > $input = 'help';
php > $output = passthru("/usr/bin/python test.py '$input'");
help

Update:

Based on your comment. You're looking for exec() instead:

~ # php -a     
Interactive shell

php > $input = 'help';
php > $output = exec("/usr/bin/python test.py '$input'");
php > echo $output;
help

Note that your Python script has to output something. Just assigning a variable is not going to work, since PHP cannot interpret your Python code for you. It can only run the script and do something with the script's output.

Oldskool
  • 34,211
  • 7
  • 53
  • 66
  • Thanks for you answer, but I am trying to return the string to php and print it there. Not in my python script. – Christian Feb 16 '18 at 12:41
  • @Christian Then use `exec` instead. But your Python script must output the desired return value if PHP is ever going to be able to catch it. PHP cannot "interpret" your Python for you. You need to output something. – Oldskool Feb 16 '18 at 12:45
  • I see. print(json2) does not actually print to screen, echo $output does. That was a hard lesson to learn. Many thanks @Oldskool – Christian Feb 16 '18 at 13:01