Shell_exec returns PHP 中为 NULL

Shell_exec returns NULL in PHP

我正在做这个项目,需要我在 PHP 上传图片,在 python 执行图片,从 python 获取输出并在 [=] 再次显示34=]。

PHP代码:

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

Python代码:

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'));

如您所见,只有一个打印命令。 Shell_exec 应该是 return 来自 python 的打印命令的字符串。但是我在 "var_dump" 上得到的是 NULL,如果我回显 $jadi,也什么也没有。无论是使用 print 还是 print(json) 命令

有趣的是,当我尝试显示这个 python 文件中仅包含 1 行代码的字符串时。

Python 虚拟文件:

print("Hello")

"Hello" 字符串在我的 PHP 上显示得很好。那么,shell_exec是不是很多代码都看不懂?还是我做错了什么?

我在控制台测试过这个:

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"
}

您必须将其包裹在 {} 或 [] 中,然后将其读入对象或数组。

出现错误后,您可以 运行 这个 json_last_error() http://php.net/manual/en/function.json-last-error.php 它会给您一个错误代码,您的 returns 应该是 JSON_ERROR_SYNTAX

终于找到原因了。在我的 python 脚本中有这些命令:

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

他们加载了我在 KNN 训练过程中存储的 numpy 数组,我需要再次使用它们作为我在 python 中图像分类过程的参考。我将它们分开是因为我担心我的 PHP 页面加载时间太长。在最终对上传的图像进行分类之前,它需要处理所有的训练数据。 但是当我从 PHP 执行我的 python 文件时,我猜它 returns 在解析这 2 个加载命令后出现错误。我尝试将打印命令放在它们下面,但它在 PHP 上停止显示。既然都这样了,那也只能选择最坏的选择,哪怕加载时间很长。