Calling PYTHON script through PHP

Asked

Viewed 242 times

1

I want PHP to show the result of PYTHON code

PYTHON

x = 4 * 5
print(x)

PHP

<?php
$teste = shell_exec('python codigopython.py 2>&1');
echo $teste; ?>

The result I’m getting is:

'python' is not recognized as an internal or external command, a operable program or a batch file.

But if I run python code on CMD, it works normally

  • And where is your Python? is where it can be accessed universally by the operating system?

  • is along with index.php on the path: C: wamp64 www test-php-python codigopython.py I’ve tried using shell_exec with the path, but gives the same result. shell_exec('python C: wamp64 www test-php-python python codigopython.py 2>&1'); 'python' is not recognized as an internal or external command, a operable program, or a batch file.

  • 3

    Caio, I believe the question was whether your Python interpreter is accessible, not whether your Python script is accessible.

  • user140828, I think so, because shell_exec is getting to the python code, but when it comes to executing, it’s not working.

  • If you gave the error cited, Windows is not locating the Python interpreter on your machine - so it doesn’t even "get to the code". Check whether the Python executable is in your PATH environment variable or run by passing the interpreter absolute path.

  • Thanks Anderson Carlos Woss, the PATH is correct, but it only worked by passing the absolute path of the interpreter.

Show 1 more comment

1 answer

-2

Use this

<?php

$comando = escapeshellcmd('./ficheiro_python.py');
$cmdResult = shell_exec($comando);
echo $cmdResult;

?>

As line "shebang" you should have the following in the python file:

#!/usr/bin/env python

You should also have permissions to run that file.

Successfully tested with Ubuntu 16, PHP7.0 and python 2.7.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.