Robbie White
Robbie White

Reputation: 31

Executing Python program that has parameters and use the result as PHP variable? (CodeIgniter, TextBlob, Python 3.4, PHP 7)

I have a PHP script that is connected to a database. The idea behind the following array is that this information is inserted into the database. The category needs to be set by an ML algorithm, for which I am using textblob for Python. I am using the codeigniter PHP framework.

$temp = $this->input->post('issue');
$data = array(
   'priority' => '1',
   'Summary' => $this->input->post('issue'),
   'status' => 'Submitted',
   'category' => exec("python machineLearning.py .$temp"),
   'itemsRequired' => ' ',
   'lastUpdate' => date('Y-m-d G:i:s'),
   'ownerID' => $this->session->userdata('username'),
   'managerID' => 'tech'
);

The python script (machineLearning.py) works fine when called on its own. The error I am getting is that the category is currently left as an empty string. I tried to use a test with:

exec("python machineLearning.py idCard", $output);
print_r($output);

But the result is just an empty array:

Array()

The python program has the machine learning inside of a function named machineLearning and takes in a parameter, named issue. I need to pass the value of

$this->input->post('issue')

into the machineLearning function in the python program. Am I passing the parameters incorrectly or does the exec() function require the correct path to the program? Thanks all.

SOLUTION FOUND

A combination of the two current arguments has solved the problem, I had to update my path to the file, inside of the exec() function, and update the parameter section of the exec function(), but had to additionally use the if statement suggested. Thank you both for your help

Upvotes: 1

Views: 1528

Answers (2)

cwallenpoole
cwallenpoole

Reputation: 82038

It looks like you probably have an error condition and so aren't getting valid data returned from exec. Try adding 2>&1 to the call and debugging output. For example, locally, I try that and I get:

exec("python machineLearning.py idCard 2>&1", $output);
print_r($output);


Array
(
    [0] => /usr/bin/python: can't open file 'machineLearning.py': [Errno 2] No such file or directory
)

You might want to specifically code the absolute path to the file in your call too. This would resolve the above "file not found" error.

exec("python /path/to/machineLearning.py idCard 2>&1", $output);

Upvotes: 1

Dragos Pop
Dragos Pop

Reputation: 458

You need to have a "main" for your python script that reads the parameter from command line and calls your function. Something like:

if __name__ == "__main__": 
    YourFunction(sys.argv[1])

Maeby add some debuge code to print your arguments. About the path to executable, if the PATH envinronment is set corectly in your php (your server?) context, to contain the path to python, you do not need the complete path to your exe.

Upvotes: 0

Related Questions