pythonraspberry-piraspberry-pi4

How can I set the display environment variable on a Raspberry Pi at boot?


I have a Raspberry Pi 4 with a 1280x800 display and no keyboard or mouse. I ssh into it remotely over WiFi and am coding it to display images, ultimately on its own without my ssh into it. I installed feh and am using it in a python script to display an image:

import subprocess
image = subprocess.Popen(["feh", "--hide-pointer", "-x", "-q", "-B", "black", "-g", "1280x800", "./test.jpg"])

I can get this code to work if I type into the command line

export DISPLAY=:0.0

beforehand. However, I would like to have that automatically at boot so that I can run the python code at boot as well and have it run autonomously. I tried putting that line into /etc/profile, but it didn't work.

Sorry for my operating system naïveté--it's a real weakness. And thanks in advance for any help.


Solution

  • I finally got this to work. I used feh to display images. You should install feh with

    sudo apt-get install feh 
    

    The python program to run is (obviously replace /home/craign with your own location):

    #!/usr/bin/env python3
    
    import os
    import subprocess
    import time
    
    # Set the HOME environment variable
    os.environ['HOME'] = '/home/craign'  # Replace with the correct home directory
    
    # Set the DISPLAY environment variable
    os.environ['DISPLAY'] = ':0'
    
    # Run xhost to allow X server access (you might need to install xhost: sudo apt-get install x11-xserver-utils)
    subprocess.run(['xhost', '+local:'], check=True)
    
    # Display the image
    image = subprocess.run(["feh", "--hide-pointer", "-x", "-q", "-F", "-B", "black", "-g", "1280x800", "/home/craign/image.jpg"])
    

    To run the program at boot:

    sudo nano /etc/rc.local
    

    Add this line before the exit 0 at the end of the file:

    python3 /home/craign/main.py &
    

    Of course make sure everything is executable.