We have moved our forum to GitHub Discussions. For questions about Phalcon v3/v4/v5 you can visit here and for Phalcon v6 here.

PHP running Python


I do know that this is not relatated to Phalcon BUT I really need to know the solution for my problem!

I am trying to run a Python script in PHP from the exec command. Works fine in terminal, but when i run it in PHP i get the following error:

Array (
[0] => sh: sysctl: command not found
[1] => Traceback (most recent call last):
[2] => File "../server/search.py", line 5, in
[3] => from pyimagesearch.colordescriptor import ColorDescriptor
[4] => File "/Applications/MAMP/htdocs/toys/server/pyimagesearch/colordescriptor.py", line 3, in
[5] => import cv2
[6] => File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/cv2/__init__.py", line 6, in
[7] => os.environ["PATH"] += os.pathsep + os.path.dirname(os.path.realpath(__file__))
[8] => File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/UserDict.py", line 40, in __getitem__
[9] => raise KeyError(key)
[10] => KeyError: 'PATH'

My PHP script:

$response = exec("python ../server/search.py 2>&1", $output, $return);
echo $return;

I think that when I run it in the webserver it can't find cv2 and "from pyimagesearch.colordescriptor" wich is in the folder

Sorry that it is not related to Phalcon, but if there is someone that can't spot the problem i would be thanksfull!

edited Nov '17

As you can see there is environment related issue:

sysctl: command not found

You should use full path to thesysctl programm or amend your (php process owner) PATH variable by adding sysctl directory.

To achieve this, you can take advantage of which or command. On some Macs, sysctl is located in /sbin/ instead of /usr/sbin/.

So you'd like to use Python program from PHP web app, and all of that on Mac / MAMP? Good luck with that :)

Anyways stick to absolute paths when you need/want to do something like this. If you have a way - build up a microservice from that Python program, and call it via HTTP / REST. If not, you have to go down the command line and parse it's output. Two apps sholuld communicate in a different manner, again, if you have a way/choice.