Python script Executable


#1

Hi,

It’s there a simple way to turn a Python script into an Executable file than CRON can run automatically at boot.

I’m very much a novice but keen to automate several scripts I have.

Thanks

Scott


#2

I run my python files via crontab. I run run sudo crontab -e from terminal and add as an example
@reboot python3 /home/pi/THP.py &


#3

Thanks Alpha

It doesn’t work for me. I’m running Raspian Stretch and my system is set to boot to CLI

I can run the script fine by opening with Geany or through the terminal.

I’m struggling to understand where I’m going wrong.

😫


#4

The Pi’s I do this on run full Jessie or Stretch but boot to command line. They run headless. I just find things so much easier to setup from full Raspbian from the GUI. Then the last thing I do is set boot to command line.

Make sure you have the @ at the start and & at the end of your crontab entry. An of course got the path to the file correct.
Something else to watch out for is using python instead of python3, and vice versa. Using just “python” runs your file in python 2 while using python3 in the command runs it in python3. I have one Pi with an older BMP180 that will only work in python 2. I mention this because a lot of the tutorials for this just list “python” in the example. Some python3 programs will crash and burn when run in python 2.


#5

Another common gotcha is dependencies.

If your Python program requires a file and references it with a relative path; say it loads an image from “myimage.jpg” then when you run it from Crontab it will look in your home directory for that file.

If you run something like “python /home/pi/Pimoroni/inkyphat/someexample.py” and it needs the file “/home/pi/Pimoroni/inkyphat/background.jpg” you would have to create a startup script to ensure the python script is launched from the right directory:

IE a file called /home/pi/start.sh that looks like this:

#!/bin/bash
cd /home/pi/Pimoroni/inkyphat
python someexample.py

Is made executable with chmod +x start.sh

And started at boot with @reboot /home/pi/start.sh


#6

Thanks Alpha & Phil, I’ll have a play later see if I can get it going.


#7

We’re working now! thx