Search code examples
pythonbashraspberry-piraspbian

bash script in rc.local different result than executing it in terminal


I'm trying to run a python script from a headless raspberrypi that uses the pynput library. In order to use pynput on a headleass machine it requires you to do the following steps on every bootup:

export DISPLAY=:0 
DISPLAY=:0 python -c 'import pynput'

If I don't do this I get the following error:

ImportError: this platform is not supported: ('failed to acquire X connection: >

Try one of the following resolutions:

  • Please make sure that you have an X server running, and that the DISPLAY env>

If I now try to automaticate this process through a bash script that contains the following lines:

#!/bin/bash
    sleep 60
    export DISPLAY=:0
    sudo chmod 666 /dev/hidg0
    DISPLAY=:0 python -c 'import pynput'
    python3 /home/pi/Hid.py |& tee -a /home/pi/test.log
exit 0

And execute the file normally like this from terminal:

bash /home/pi/bash.sh

it works perfectly fine. But when I mention the script in the rc.local file the same way I executed it before, the script is getting executed on boot, but the python script throws the error that was shown at the beginning. How can there be two different outcomes, when it's getting executed by hand and when it's getting executed by a bash script at boot via. rc.local? Any help is appreciated!


Solution

  • All commands from rc.local are getting executed by user root. To execute them from a different user use:

    sudo su USERNAME -c 'SCRIPT/PATH'