Home > Enterprise >  Python script not able to find package when executed from terminal at bootup, what am I doing wrong?
Python script not able to find package when executed from terminal at bootup, what am I doing wrong?

Time:06-03

sorry in case this is obvious or redundant, I've been looking around on this site for an answer to this problem but I couldn't find anything that would fix it

What I am trying to achieve is executing a python script when my raspberry pi turns on (after the desktop loads in)

I've been trying to do so by adding these lines at the end of /home/pi/.bashrc

echo Running at boot

sudo /usr/bin/python3.7m  /home/pi/Desktop/Program/NameOfTheProgram.py

The problem, as you might've guessed from the title, is that when the script is executed as I open the terminal, and consequently at bootup, python doesn't appear to be capable of finding a package

    from SSIM_PIL import compare_ssim as ssim #Import ssim from ssim package
ModuleNotFoundError: No module named 'SSIM_PIL'

This problem does not arise when I execute the script from the terminal by using

/usr/bin/python3.7m  /home/pi/Desktop/Program/NameOfTheProgram.py

in wich case the program is executed as intended, so my only guess is that this shouldn't be a problem with the python version I'm using, since I'm 100% sure it's the same one and it apparently should work, but I may be mistaken

I've also tried to put those same lines of code in /etc/rc.local, but to no avail

Am I missing something? Thank you in advance

CodePudding user response:

It is me again, like Roberto pointed out removing sudo from the command did indeed work to execute the program when a terminal window is opened

Unfortunately this didn't initiate the program at startup, but in theory all I need to do now is find a way to open a terminal window with a terminal command, and the program should be working correctly

This is admittedly a bit contrived, but it's good enough as long as the program works

To open the terminal on boot I've edited the autostart file in the lxsession folder by adding @lxterminal to it, as illustrated in this answer

I'm answering to my own question as I don't know how to mark a comment as "answer", if that's even possible

CodePudding user response:

It is possible to run scripts at different moments:

  1. At system boot (see this answer on superuser, or use cron's @reboot feature).
  2. When users log in to their shell.
  3. When users open a new terminal.
  4. On an arbitrary given time (using cron and crontab; read the manual pages!)

Concerning 2 and 3; this depends somewhat on the shell you use. Read the manual of the user's shell and look in the FILES section.

If a script does not require root privileges, I'm a fan of using cron, because it supports running commands as a non-root user.

  • Related