0

So, I have a python script that uses machine learning models to predict and print a string. Running the script alone gives desired output and takes around 12 seconds to complete. Now calling the python script using a custom wordpress rest api endpoint returns null. I tried running the standard hello world python script, and it works fine. After trying many things and variations, I have discovered that importing the libraries is causing the issue. To be precise importing the numpy.array and/or joblib from sklearn.externals is somehow causing the output to be null. Here is the python code

#!C:\xampp\htdocs\mil\Scripts\python.exe

from datetime import datetime 
import json
from numpy import array
from sklearn.externals import joblib
import traceback

print("hello")

And here is the php code I am using inside the custom rest api get function

$topy = 'python C:\xampp\htdocs\mil\mypython\venv\test.py';
$command = escapeshellcmd($topy);
$output = shell_exec($command);
return $output;

I have also tried these 2 alternatives but the problem continues, I get blank string as output. 1.

ob_start();
passthru('python C:\Users\Deepon\PycharmProjects\Home\test.py');
$output = ob_get_clean(); 
return $output;

2.

$descriptorspec = array(
   0 => array("pipe", "r"),
   1 => array("pipe", "w"),
   2 => array("file", "error-output.txt", "a")
);


$process = proc_open('python C:\xampp\htdocs\mil\mypython\venv\test.py', $descriptorspec, $pipes);

if (is_resource($process)) {

print fgets($pipes[1]);
$return_value = proc_close($process);

return $return_value;
}

So fellas , any ideas on how to solve this dilemna of mine ?

  • 1
    This sounds more like a general Python/PHP question than anything really to do with WordPress. You'll have a better chance getting an answer at stackoverflow.com. – Jacob Peattie Apr 24 at 14:51
0

Thanks @JacobPeattie. I realize now after going through a few more articles that the problem was indeed not with wordpress but php and i was looking at the wrong place. The solution I found, I will write it down here just in case:

putenv('PYTHONPATH=C:\xampp\htdocs\mil\mypython\venv\Lib\site-packages');

The problem was indeed with php. I found the answer only after removing wordpress from the search query.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.