Monday, February 21, 2022

[SOLVED] Python subprocess.popen from within a cron job

Issue

I'm trying to setup a server to run on startup (Raspberry Pi) - the server calls a script which calls a script...except they're not firing.

  1. add the cron job using crontab -e and writing @reboot python3 /path/to/my_server.py (also tested with & at end of line)...this works fine.
  2. my_server.py uses httpd.server_forever() to listen at a few endpoints...this works fine.
  3. One of the server endpoints runs subprocess.Popen(['python3', '/path/to/my_script.py']).
  4. my_script.py then runs subprocess.Popen(['qgis']) (also tried with shell=True).

However, QGIS isn't starting.

This is only happening when trying to run everything on boot with the cron job. If I manually open a terminal and run python3 /path/to/my_server.py then everything works as expected. I'm thinking it has to do with...things not being run in a shell/terminal - maybe a behavior of Popen?


Solution

The issue is that QGIS requires x server to be running, and cron won't have that by default.

Fix: change cron entry to be @reboot export DISPLAY=:0; python3 /path/to/my_server.py and everything works!



Answered By - Antoine Zambelli
Answer Checked By - Gilberto Lyons (WPSolving Admin)