PHP exec cannot execute Python script

Question:

I use PHP in Windows 11. I cannot execute Python script in PHP exec.

The current situation is as follows, Commands that do not call Python scripts can be executed:

exec("cd E:/Python/WordFrequency && ipconfig", $output, $result_code);

exec("Python -V", $output, $result_code);

The above two lines of code return code 0.

However, the following code returns code 1:

exec("Python E:/Python/Mnist/main.py", $output, $result_code);

Run directly in Windows PowerShell:

Python E:/Python/Mnist/main.py

There is no problem.

However, calling in PHP returns code 1.

What’s the matter, please?

Asked By: small tomato

||

Answers:

After hard work, I have solved this problem a few days ago. Now, I put the solution here.

The reason why PHP cannot call Python files is that when executing the following command in exec():

Python E:/Python/Mnist/main.py

The following error was returned:
RuntimeError: Could not determine home directory.

After further testing, it was found that:

import os
import numpy as np
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers

It is found that PHP can successfully call Python if main.py contains only the above five lines of code. This means that my entire PHP and Python program logic and operating system permissions are all right.

And once I add another line of code:

from matplotlib import pyplot as plt

PHP will not be able to call Python successfully, and will prompt the error message "Could not determine home directory". This means the error introduced by the code from matplotlib import pyplot as plt.

At the beginning, I thought there was a problem with the path or permissions of matplotlib installation. After inspection, there are no problems.
After inquiring more information, I gradually understood the reason. For the module matplotlib, it will ask to determine the user’s home directory. Because usually only the users of the operating system call the matplotlib module, which is meaningful and won’t cause trouble. However, unspecified visitors who call Python scripts through browsers will not own or determine the user’s home directory. Therefore, in this case, it is very reasonable for the matplotlib module to throw an error that cannot determine the user’s home directory.

How to solve the problem of Could not determine home directory?
The method is to add the following code before the line from matplotlib import pyplot as plt (or directly at the beginning of the Python file):

import os
os.environ['HOMEPATH'] = 'E:/Python/Mnist'

That is, the home directory of the unspecified user who accesses the Python script through the browser is manually specified. So as to provide matplotlib with a place where necessary files can be saved.

Answered By: small tomato
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.