简体   繁体   中英

Shell_exec returns NULL in PHP

I am working on this project that requires me to upload pictures on PHP, execute the picture on python, fetch the output from python and display it again on PHP.

PHP code:

<?php 
$command = shell_exec("python C:/path/to/python/KNNColor.py");
$jadi = json_decode($command);
var_dump($jadi);
?>

Python code:

from PIL import Image
import os
import glob
import cv2
import numpy as np
import matplotlib.pyplot as plt
from skimage import io, color
from scipy.stats import skew

#data train untuk warna
Feat_Mom_M = np.load('FeatM_M.npy')
Feat_Mom_I = np.load('FeatM_I.npy')

Malay_Col_Train = Feat_Mom_M

Indo_Col_Train = Feat_Mom_I

#Data warna
All_Train_Col = np.concatenate((Malay_Col_Train, Indo_Col_Train))

Y_Indo_Col = [0] * len(Indo_Col_Train)
Y_Malay_Col = [1] * len(Malay_Col_Train)

Y_Col_Train = np.concatenate((Y_Malay_Col, Y_Indo_Col))

Train_Col = list(zip(All_Train_Col, Y_Col_Train))

from collections import Counter 
from math import sqrt
import warnings 

#Fungsi KNN
def k_nearest_neighbors(data, predict, k):
   if len(data) >= k:
       warnings.warn('K is set to a value less than total voting groups!')
   distances = []
   for group in data:
      for features in data[group]:
        euclidean_dist = np.sqrt(np.sum((np.array(features) - np.array(predict))**2 ))
        distances.append([euclidean_dist, group])

votes = [i[1] for i in sorted(distances)[:k]]
vote_result = Counter(votes).most_common(1)[0][0]

return vote_result

image_list = []

image_list_pixel = []

image_list_lab = []

L = []
A = []
B = []

for filename in glob.glob('C:/path/to/pic/uploaded/batik.jpg'):
   im=Image.open(filename)
   image_list.append(im)
   im_pix = np.array(im)
   image_list_pixel.append(im_pix)
   #ubah RGB ke LAB
   im_lab = color.rgb2lab(im_pix)
   #Pisah channel L,A,B
   l_channel, a_channel, b_channel = cv2.split(im_lab)
   L.append(l_channel)
   A.append(a_channel)
   B.append(b_channel)
   image_list_lab.append(im_lab)

 <The rest is processing these arrays into color moment vector, it's too long, so I'm skipping it to the ending>

   Feat_Mom = np.array(Color_Moment)

   Train_Set_Col = {0:[], 1:[]}

for i in Train_Col:
    Train_Set_Col[i[-1]].append(i[:-1])

new_feat_col = Feat_Mom

hasilcol = k_nearest_neighbors(Train_Set_Col, new_feat_col, 9)

 import json
 if hasilcol == 0:
    #print("Indonesia")
    print (json.dumps('Indonesia'));
 else:
    #print("Malaysia")
    print (json.dumps('Malaysia'));

So as you can see, There is only one print command. Shell_exec is supposed to return the string of the print command from python. But what I get on the "var_dump" is NULL, and if I echo $jadi, there's also nothing. Be it using print or the print(json) command

The fun thing is, when I try to display a string from this python file that only consists 1 line of code.

Python dummy file:

print("Hello")

The "Hello" string, shows up just fine on my PHP. So, is shell_exec unable to read many codes? or is there anything else that I'm doing wrong?

I finally found the reason behind this. In my python script there are these commands :

Feat_Mom_M = np.load('FeatM_M.npy')
Feat_Mom_I = np.load('FeatM_I.npy')

They load the numpy arrays that I have stored from the training process in KNN and I need to use them again as the references for my image classifying process in python. I separated them because I was afraid if my PHP page would take too long to load. It'd need to process all the training data, before finally classifying the uploaded image. But then when I execute my python file from PHP, I guess it returns an error after parsing those 2 load commands. I experimented putting the print command below them, and it stopped showing on PHP. Since it's all like this now, there's no other way than taking the worst option, even if it'd cost me long loading time.

I tested this in the console:

php > var_dump(json_decode("Indonesia"))
php > ;
php shell code:1:
NULL
php > var_dump(json_decode('{"Indonesia"}'))
php > ;
php shell code:1:
NULL
php > var_dump(json_decode('{"Indonesia":1}'))
php > ;
php shell code:1:
class stdClass#1 (1) {
  public $Indonesia =>
  int(1)
}
php > var_dump(json_decode('["Indonesia"]'))
php shell code:1:
array(1) {
  [0] =>
  string(9) "Indonesia"
}

you have to have it wrapped in {} or [] and it will be read into an object or an array.

After an error you can run this json_last_error() http://php.net/manual/en/function.json-last-error.php and it will give you an error code the one your's returns should be JSON_ERROR_SYNTAX

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM