2

Hi am having trouble passing a variable from PHP to python. It is not displaying on the webpage

PHP

<?php 
  $item='example';
  exec("python pytest.py $item");
?>

Python

import sys
print(sys.argv[1])

I am running WAMP and both the PHP and Python file is in the same working directory. However, nothing is displayed on the PHP webpage. Please help, thank you.

  • Do you have [PHP error reporting](https://stackoverflow.com/questions/1053424/how-do-i-get-php-errors-to-display) enabled? Maybe it throws an exception. Maybe you do not have the rights to execute such commands? Other logs might help as well (Python and/or System). – Definitely not Rafal Feb 05 '21 at 08:35

2 Answers2

0

I think the only thing you are missing in your PHP script is echo.

If you call exec("python pytest.py $item"); PHP won't just print the output of the called command.

You need to echo shell_exec("python pytest.py $item");.

The difference between exec and shell_exec is that shell_exec will return the output of the command but exec won't. You can read more about it here: https://www.php.net/manual/en/function.shell-exec.php and https://www.php.net/manual/en/function.exec.php.

Also make sure the user, which is running the PHP-File, has permissions on the pytest.py file.

Noxic
  • 13
  • 3
-1

To call a Python file from within a PHP file, you need to call it using the shell_exec function.

For example

<?php
    $command = escapeshellcmd('/usr/custom/test.py');
    $output = shell_exec($command);
    echo $output;
?>

This will call the script. But in your script at the top, you'll need to specify the interpreter as well. So in your py file, add the following line at the top:

#!/usr/bin/env python

Alternatively you can also provide the interpreter when executing the command.

For example

<?php
    $command = escapeshellcmd('python3 /usr/custom/test.py');
    $output = shell_exec($command);
    echo $output;
?>

other alternate way to do is

ob_start();
passthru('/usr/bin/python2.7 /srv/http/assets/py/switch.py arg1 arg2');
$output = ob_get_clean(); 
Akash senta
  • 349
  • 3
  • 12