0

I want to send a string to python function from a form in php file.

The python function which receives the "string argument" will process it and return the "result string" back in the same php file and display it.

Please guide me how to do it.

Update I am using xampp server on Windows8.1, and Python3.6.4 I have used shell_exec() successfully to send arguments from php to python but unable to return variable back to php from python.

My PHP code: (index.php)

$param1 = "abc";
$param2 = "xyz"
shell_exec("python C:/python/echo.py $param1 $param2");

My python code (echo.py)

import sys
x = sys.argv[1]
y = sys.argv[2]
print(x)
print(y)
#here I want to return string
#return "code executed successfully"
# and receive this sentence back in new.php file & display it with proper css

(Note: I have already read answers to many similar questions on StackOverflow but couldn't find an answer specific to this scenario)

Khan
  • 27
  • 1
  • 8
  • @ObsidianAge this is a similar question but not a duplicate. The nature and scenario explained in my question is very different. Please help if you can. Thanks :) – Khan Apr 08 '18 at 22:54
  • @James I have updated the question. – Khan Apr 09 '18 at 11:23

2 Answers2

2

Assigning the shell_exec to a variable($resultAsString) seems to be the solution for me.

The PHP:

<?php 

  //your variables that you are assigning
    $param1 = 'one';
    $param2 = "two";
  //This is where you pass the variables into Python 
    $command = escapeshellcmd("/python/echo.py $param1 $param2");
  //assign the execution to a variable
    $resultAsString = shell_exec($command);
    echo $resultAsString;
?>

The Python:

import sys
ResultAsString = ''

#some computing as an example
for x in sys.argv:
    if (x == sys.argv[0]):
        continue
    else:    
        ResultAsString += str(x)+" "

#everything you print will be returned to PHP as a single string
print(ResultAsString)
1

Manual for shell-exec:

This function can return NULL both when an error occurs or the program produces no output. It is not possible to detect execution failures using this function. exec() should be used when access to the program exit code is required.

Manual for exec:

string exec ( string $command [, array &$output [, int &$return_var ]] )

return_var
If the return_var argument is present along with the output argument, then the return status of the executed command will be written to this variable.

 

Try this (untested code so test it):

exec('python C:/python/echo.py',  ['abc', 'xzy'], $return_value);

The $return_value is what you are looking for.

James
  • 4,644
  • 5
  • 37
  • 48