简体   繁体   中英

Executing Python script with pyautogui from PHP

Hello I am trying to execute a Python script with pyautogui library from PHP on apache2 server running on a Raspberry Pi. While executing the Python script from the command line I encounter no problems, but when doing so through PHP's "shell_exec" I get following error message:

error.log in apache2:

Traceback (most recent call last): File "/home/pi/Projects/Python/wakeUp.py", line 2, in import pyautogui File "/usr/local/lib/python3.4/dist-packages/pyautogui/ init .py", line 115, in from . import _pyautogui_x11 as platformModule File "/usr/local/lib/python3.4/dist-packages/pyautogui/_pyautogui_x11.py", line 160, in _display = Display(os.environ['DISPLAY']) File "/usr/lib/python3.4/os.py", line 633, in getitem raise KeyError(key) from None KeyError: 'DISPLAY'

Python script (test.py):

#!/usr/bin/python3 
import pyautogui 
pyautogui.moveTo(25, 25, duration=1) 
pyautogui.click()

PHP script (index.php):

<?php
shell_exec("python3 /home/pi/Projects/Python/test.py");
?>

I have been stuck on this issue for weeks now, everything works separately, but when put together I get the error message, if anyone could help I would appreciate it a lot. Thanks.

You are not setting the DISPLAY variable, so pyautogui does not know where to display its screen.

You can use Apache mod_env to set the display variable, and them load the PHP loading PyAutoGUI.

And there's another catch: probably Apache is running under user nobody , or www-data . Your user usually is something else. Any process started by Apache will not have access to your display.

You could remove Apache and PHP from the solution, and use pure python insted:

export DISPLAY=:0
mkdir cgi-bin
python3 -m http.server --bind localhost --cgi 8000

Put your test.py inside cgi-bin, and add this at the end of the file: print("Content-Type: text/html\\n") print("OK")

Accessing http://localhost:8000/cgi-bin/test.py will run the script, with the correct variables.

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