I have written a Python script that removes the background of an image using the rembg library and then composes the image using PIL.
For this project, a virtualenv was created and rembg was installed there.
All of this is on an Ubuntu 20.04 server.
The project folder is located at /var/www/work/py/banner_generator and contains a virtual environment folder called venv. The Python script itself is located at /var/www/work/py/banner_generator/banner_generator.py. If I run the command /var/www/work/py/banner_generator/venv/bin/python3.8 /var/www/work/py/banner_generator/banner_generator.py from the console, it works as intended.
However, I need to run this script in a PHP script. When I execute the code in PHP:
$cmd = "/var/www/work/py/banner_generator/venv/bin/python3.8 /var/www/work/py/banner_generator/banner_generator.py";
$output = shell_exec($cmd);
echo $output;
Nothing happens. When I commented out the code and left only "print("work")" in the Python script, everything worked from PHP.
I decided to comment out my code and test it. First, in the Python script, I left only "print("work")" and checked it. In this case, everything worked from PHP. Then I decided to continue experimenting and uncommented all my imports, resulting in the following code:
import argparse
import os
from rembg import remove
from PIL import Image, ImageDraw, ImageFilter, ImageEnhance
import requests
from io import BytesIO
print("work")
I ran it again and it didn't work. The "work" statement didn't show up.
Then I started commenting out some imports and, through trial and error, discovered that the problem only occurred when importing rembg. In other words, the following code works:
import argparse
import os
# from rembg import remove
from PIL import Image, ImageDraw, ImageFilter, ImageEnhance
import requests
from io import BytesIO
print("work")
Interesting fact: PIL is only installed in the virtual environment, yet its import does not cause any problems. However, for some reason, importing rembg causes issues.
You could try setting the PYTHONPATH environment variable to include the path to the rembg library in your PHP script before running the Python script. For example: