Banyanss
Posts: 23
Joined: Sat May 13, 2017 8:01 am

Running python script on startup

Sun Dec 17, 2017 4:47 pm

Hello everyone,

Ive been trying for a little while now to get my python script to run on boot but nothing seems to work so I can only assume I am doing something incorrectly (ive tried /etc/rc.local, crontab, systemd etc...)

My file is called launch.py and its path is /home/pi/IMS/

Anyone have any ideas? im not getting errors just nothing happens on boot.

Many Thanks!

User avatar
DougieLawson
Posts: 35801
Joined: Sun Jun 16, 2013 11:19 pm
Location: Basingstoke, UK
Contact: Website Twitter

Re: Running python script on startup

Sun Dec 17, 2017 5:00 pm

Systemd is the most reliable.

Create a file with sudo /etc/systemd/system/IMS.service

Code: Select all

[Unit]
Description=Get IMS service running at boot
After=mosquitto.service mysql.service

[Service]
ExecStart=/home/pi/IMS/launch.py
Restart=always
StandardOutput=syslog
StandardError=syslog
SyslogIdentifier=IMS
User=pi
Group=pi

[Install]
WantedBy=multi-user.target
In my example the After clause means it won't start before Mosquitto or MySQL (that's optional). I've also got Restart=always to trap failures and restart the process.

Enable it with sudo systemctl enable IMS.service
Start it (this boot only) with sudo systemctl start IMS.service
Find if it's running with systemctl status IMS.service
Note: Having anything humorous in your signature is completely banned on this forum. Wear a tin-foil hat and you'll get a ban.

Any DMs sent on Twitter will be answered next month.

This is a doctor free zone.

Banyanss
Posts: 23
Joined: Sat May 13, 2017 8:01 am

Re: Running python script on startup

Sun Dec 17, 2017 5:13 pm

Thanks Dougie,

That worked perfectly. I must have not been following the instructions properly previously.

Thanks again!

Geeman2000
Posts: 34
Joined: Mon Jun 15, 2015 7:17 am

Re: Running python script on startup

Mon Dec 18, 2017 9:07 am

When I saw the thread title I thought I couldn't miss an opportunity for a better way to auto start a python script at boot. I have adapted Dougie's code to suit my situation, running a python script to get temperatures from i2c bus - 1Wire devices and log to data base. The script is named tempbus.py and runs with

Code: Select all

python /home/pi/work/tempbus.py


The code below is in file /etc/systemd/system/ tempbus.service

Code: Select all

[Unit]
Description=Get temperature logging service running at boot
After=mosquitto.service mysql.service

[Service]
ExecStart=/home/pi/work/tempbus.py
Restart=always
StandardOutput=syslog
StandardError=syslog
SyslogIdentifier=tempbus
User=pi
Group=pi

[Install]
WantedBy=multi-user.target
However it doesn't go smoothly.

Code: Select all

[email protected]:/etc/systemd/system $ sudo systemctl enable tempbus.service
[email protected]:/etc/systemd/system $ sudo systemctl start tempbus.service
[email protected]:/etc/systemd/system $ systemctl status tempbus.service
● tempbus.service - Get temperature logging service running at boot
   Loaded: loaded (/etc/systemd/system/tempbus.service; enabled; vendor preset: enabled)
   Active: failed (Result: exit-code) since Mon 2017-12-18 17:00:32 AWST; 18s ago
  Process: 13226 ExecStart=/home/pi/work/tempbus.py (code=exited, status=203/EXEC)
 Main PID: 13226 (code=exited, status=203/EXEC)

Dec 18 17:00:32 RPI-3 systemd[1]: tempbus.service: Service hold-off time over, scheduling restart.
Dec 18 17:00:32 RPI-3 systemd[1]: Stopped Get temperature logging service running at boot.
Dec 18 17:00:32 RPI-3 systemd[1]: tempbus.service: Start request repeated too quickly.
Dec 18 17:00:32 RPI-3 systemd[1]: Failed to start Get temperature logging service running at boot.
Dec 18 17:00:32 RPI-3 systemd[1]: tempbus.service: Unit entered failed state.
Dec 18 17:00:32 RPI-3 systemd[1]: tempbus.service: Failed with result 'exit-code'.
[email protected]:/etc/systemd/system $
Any ideas on what is the issue? Is there no need to declare "python" prior to the executable?

cheers
Geeman

User avatar
DougieLawson
Posts: 35801
Joined: Sun Jun 16, 2013 11:19 pm
Location: Basingstoke, UK
Contact: Website Twitter

Re: Running python script on startup

Mon Dec 18, 2017 3:18 pm

You'll need to post /home/pi/work/tempbus.py for us to help. It's exiting with a non-zero code.
Note: Having anything humorous in your signature is completely banned on this forum. Wear a tin-foil hat and you'll get a ban.

Any DMs sent on Twitter will be answered next month.

This is a doctor free zone.

Geeman2000
Posts: 34
Joined: Mon Jun 15, 2015 7:17 am

Re: Running python script on startup

Mon Dec 18, 2017 11:03 pm

Here is the contents of tempbus.py, it was running 1Wire devices straight from RPi pins but due to wiring topography the system was unstable if I had more than about half connected. Now have i2c 8 x 1Wire bus chip and so far hooked 12 sensors up to 1 bus and it's rock solid. So I commented out some parts of the python file that I think are redundant with change of 1Wire bus. The script runs fine from command line.
I followed workings here https://skyboo.net/2017/02/raspberry-pi ... us-master/ to get the i2c device communicating and placing info in the /sys/bus/w1/devices/ folder.

(sorry for some long continuous lines, I didn't get around to working out how to break them up in python)



Code: Select all

#import os
import time
import MySQLdb as mdb
import logging


#legacy commands pre 1W bus ____os.system('modprobe w1-gpio')
#os.system('modprobe w1-therm')
#Set active sensors, 0=inactive, 1 =active
ts_1 = 1 #Hot Water
ts_2 = 1 #AC Inlet Passage
ts_3 = 1 #AC Roof Xchange Inlet
ts_4 = 0 #Pool
ts_5 = 1 #AC Kitchen Outlet
ts_6 = 1 #AC Day Room Outlet
ts_7 = 1 #AC Outside Unit Fan Inlet
ts_8 = 1 #AC Outside Unit Fan Outlet
ts_9 = 1 #Wall Cavity
ts_10 = 1 #AC Roof Xchange Outlet
ts_11 = 1 #Pool Area Ambient
ts_12 = 1 #Roof
ts_13 = 0 #Garage
ts_14 = 0 #Patio
ts_15 = 0 #Entrance

if ts_1 == 1:
    temp_sensor_1 = '/sys/bus/w1/devices/28-0000066066dd/w1_slave'
if ts_2 == 1:
    temp_sensor_2 = '/sys/bus/w1/devices/28-000006600ffd/w1_slave'
if ts_3 == 1:
    temp_sensor_3 = '/sys/bus/w1/devices/28-0316529e61ff/w1_slave'
if ts_4 == 1:
    temp_sensor_4 = '/sys/bus/w1/devices/28-800000276014/w1_slave'
if ts_5 == 1:
    temp_sensor_5 = '/sys/bus/w1/devices/28-0416556147ff/w1_slave'
if ts_6 == 1:
    temp_sensor_6 = '/sys/bus/w1/devices/28-041655fdf1ff/w1_slave'
if ts_7 == 1:
    temp_sensor_7 = '/sys/bus/w1/devices/28-041655fdc6ff/w1_slave'
if ts_8 == 1:
    temp_sensor_8 = '/sys/bus/w1/devices/28-0000066143fb/w1_slave'
if ts_9 == 1:
    temp_sensor_9 = '/sys/bus/w1/devices/28-0316526975ff/w1_slave'
if ts_10 == 1:
    temp_sensor_10 = '/sys/bus/w1/devices/28-041655e0f6ff/w1_slave'
if ts_11 == 1:
    temp_sensor_11 = '/sys/bus/w1/devices/28-000006616388/w1_slave'
if ts_12 == 1:
    temp_sensor_12 = '/sys/bus/w1/devices/28-031652f316ff/w1_slave'
if ts_13 == 1:
    temp_sensor_13 = '/sys/bus/w1/devices/28-0416557a76ff/w1_slave'
if ts_14 == 1:
    temp_sensor_14 = '/sys/bus/w1/devices/28-041655f892ff/w1_slave'
if ts_15 == 1:
    temp_sensor_15 = '/sys/bus/w1/devices/28-031652f44fff/w1_slave'

if ts_1 == 1:
    def temp_raw_1():
        f = open(temp_sensor_1, 'r')
        lines_1 = f.readlines()
        f.close()
        return lines_1
    def read_temp_1():
        lines_1 = temp_raw_1()
        while lines_1[0].strip()[-3:] != 'YES':
            time.sleep(0.2)
            lines_1 = temp_raw_1()
        temp_output_1 = lines_1[1].find('t=')
        if temp_output_1 != -1:
            temp_string_1 = lines_1[1].strip()[temp_output_1+2:]
            temp_1 = round(float(temp_string_1) / 1000.0,1)        
            return temp_1
            
if ts_2 == 1:
    def temp_raw_2():
        f = open(temp_sensor_2, 'r')
        lines_2 = f.readlines()
        f.close()
        return lines_2
    def read_temp_2():
        lines_2 = temp_raw_2()
        while lines_2[0].strip()[-3:] != 'YES':
            time.sleep(0.2)
            lines_2 = temp_raw_2()
        temp_output_2 = lines_2[1].find('t=')
        if temp_output_2 != -1:
            temp_string_2 = lines_2[1].strip()[temp_output_2+2:]
            temp_2 = round(float(temp_string_2) / 1000.0,1)        
            return temp_2

if ts_3 == 1:
    def temp_raw_3():
        f = open(temp_sensor_3, 'r')
        lines_3 = f.readlines()
        f.close()
        return lines_3
    def read_temp_3():
        lines_3 = temp_raw_3()
        while lines_3[0].strip()[-3:] != 'YES':
            time.sleep(0.2)
            lines_3 = temp_raw_3()
        temp_output_3 = lines_3[1].find('t=')
        if temp_output_3 != -1:
            temp_string_3 = lines_3[1].strip()[temp_output_3+2:]
            temp_3 = round(float(temp_string_3) / 1000.0,1)        
            return temp_3

if ts_4 == 1:
    def temp_raw_4():
        f = open(temp_sensor_4, 'r')
        lines_4 = f.readlines()
        f.close()
        return lines_4
    def read_temp_4():
        lines_4 = temp_raw_4()
        while lines_4[0].strip()[-3:] != 'YES':
            time.sleep(0.2)
            lines_4 = temp_raw_4()
        temp_output_4 = lines_4[1].find('t=')
        if temp_output_4 != -1:
            temp_string_4 = lines_4[1].strip()[temp_output_4+2:]
            temp_4 = round(float(temp_string_4) / 1000.0,1)        
            return temp_4

if ts_5 == 1:
    def temp_raw_5():
        f = open(temp_sensor_5, 'r')
        lines_5 = f.readlines()
        f.close()
        return lines_5
    def read_temp_5():
        lines_5 = temp_raw_5()
        while lines_5[0].strip()[-3:] != 'YES':
            time.sleep(0.2)
            lines_5 = temp_raw_5()
        temp_output_5 = lines_5[1].find('t=')
        if temp_output_5 != -1:
            temp_string_5 = lines_5[1].strip()[temp_output_5+2:]
            temp_5 = round(float(temp_string_5) / 1000.0,1)        
            return temp_5

if ts_6 == 1:
    def temp_raw_6():
        f = open(temp_sensor_6, 'r')
        lines_6 = f.readlines()
        f.close()
        return lines_6
    def read_temp_6():
        lines_6 = temp_raw_6()
        while lines_6[0].strip()[-3:] != 'YES':
            time.sleep(0.2)
            lines_6 = temp_raw_6()
        temp_output_6 = lines_6[1].find('t=')
        if temp_output_6 != -1:
            temp_string_6 = lines_6[1].strip()[temp_output_6+2:]
            temp_6 = round(float(temp_string_6) / 1000.0,1)        
            return temp_6

if ts_7 == 1:
    def temp_raw_7():
        f = open(temp_sensor_7, 'r')
        lines_7 = f.readlines()
        f.close()
        return lines_7
    def read_temp_7():
        lines_7 = temp_raw_7()
        while lines_7[0].strip()[-3:] != 'YES':
            time.sleep(0.2)
            lines_7 = temp_raw_7()
        temp_output_7 = lines_7[1].find('t=')
        if temp_output_7 != -1:
            temp_string_7 = lines_7[1].strip()[temp_output_7+2:]
            temp_7 = round(float(temp_string_7) / 1000.0,1)        
            return temp_7

if ts_8 == 1:
    def temp_raw_8():
        f = open(temp_sensor_8, 'r')
        lines_8 = f.readlines()
        f.close()
        return lines_8
    def read_temp_8():
        lines_8 = temp_raw_8()
        while lines_8[0].strip()[-3:] != 'YES':
            time.sleep(0.2)
            lines_8 = temp_raw_8()
        temp_output_8 = lines_8[1].find('t=')
        if temp_output_8 != -1:
            temp_string_8 = lines_8[1].strip()[temp_output_8+2:]
            temp_8 = round(float(temp_string_8) / 1000.0,1)        
            return temp_8

if ts_9 == 1:
    def temp_raw_9():
        f = open(temp_sensor_9, 'r')
        lines_9 = f.readlines()
        f.close()
        return lines_9
    def read_temp_9():
        lines_9 = temp_raw_9()
        while lines_9[0].strip()[-3:] != 'YES':
            time.sleep(0.2)
            lines_9 = temp_raw_9()
        temp_output_9 = lines_9[1].find('t=')
        if temp_output_9 != -1:
            temp_string_9 = lines_9[1].strip()[temp_output_9+2:]
            temp_9 = round(float(temp_string_9) / 1000.0,1)        
            return temp_9

if ts_10 == 1:
    def temp_raw_10():
        f = open(temp_sensor_10, 'r')
        lines_10 = f.readlines()
        f.close()
        return lines_10
    def read_temp_10():
        lines_10 = temp_raw_10()
        while lines_10[0].strip()[-3:] != 'YES':
            time.sleep(0.2)
            lines_10 = temp_raw_10()
        temp_output_10 = lines_10[1].find('t=')
        if temp_output_10 != -1:
            temp_string_10 = lines_10[1].strip()[temp_output_10+2:]
            temp_10 = round(float(temp_string_10) / 1000.0,1)        
            return temp_10

if ts_11 == 1:
    def temp_raw_11():
        f = open(temp_sensor_11, 'r')
        lines_11 = f.readlines()
        f.close()
        return lines_11
    def read_temp_11():
        lines_11 = temp_raw_11()
        while lines_11[0].strip()[-3:] != 'YES':
            time.sleep(0.2)
            lines_11 = temp_raw_11()
        temp_output_11 = lines_11[1].find('t=')
        if temp_output_11 != -1:
            temp_string_11 = lines_11[1].strip()[temp_output_11+2:]
            temp_11 = round(float(temp_string_11) / 1000.0,1)        
            return temp_11

if ts_12 == 1:
    def temp_raw_12():
        f = open(temp_sensor_12, 'r')
        lines_12 = f.readlines()
        f.close()
        return lines_12
    def read_temp_12():
        lines_12 = temp_raw_12()
        while lines_12[0].strip()[-3:] != 'YES':
            time.sleep(0.2)
            lines_12 = temp_raw_12()
        temp_output_12 = lines_12[1].find('t=')
        if temp_output_12 != -1:
            temp_string_12 = lines_12[1].strip()[temp_output_12+2:]
            temp_12 = round(float(temp_string_12) / 1000.0,1)        
            return temp_12

if ts_13 == 1:
    def temp_raw_13():
        f = open(temp_sensor_13, 'r')
        lines_13 = f.readlines()
        f.close()
        return lines_13
    def read_temp_13():
        lines_13 = temp_raw_13()
        while lines_13[0].strip()[-3:] != 'YES':
            time.sleep(0.2)
            lines_13 = temp_raw_13()
        temp_output_13 = lines_13[1].find('t=')
        if temp_output_13 != -1:
            temp_string_13 = lines_13[1].strip()[temp_output_13+2:]
            temp_13 = round(float(temp_string_13) / 1000.0,1)        
            return temp_13

if ts_14 == 1:
    def temp_raw_14():
        f = open(temp_sensor_14, 'r')
        lines_14 = f.readlines()
        f.close()
        return lines_14
    def read_temp_14():
        lines_14 = temp_raw_14()
        while lines_14[0].strip()[-3:] != 'YES':
            time.sleep(0.2)
            lines_14 = temp_raw_14()
        temp_output_14 = lines_14[1].find('t=')
        if temp_output_14 != -1:
            temp_string_14 = lines_14[1].strip()[temp_output_14+2:]
            temp_14 = round(float(temp_string_14) / 1000.0,1)        
            return temp_14

if ts_15 == 1:
    def temp_raw_15():
        f = open(temp_sensor_15, 'r')
        lines_15 = f.readlines()
        f.close()
        return lines_15
    def read_temp_15():
        lines_15 = temp_raw_15()
        while lines_15[0].strip()[-3:] != 'YES':
            time.sleep(0.2)
            lines_15 = temp_raw_15()
        temp_output_15 = lines_15[1].find('t=')
        if temp_output_15 != -1:
            temp_string_15 = lines_15[1].strip()[temp_output_15+2:]
            temp_15 = round(float(temp_string_15) / 1000.0,1)        
            return temp_15

while True:
    tv_1 = -20
    tv_2 = -20
    tv_3 = -20
    tv_4 = -20
    tv_5 = -20
    tv_6 = -20
    tv_7 = -20
    tv_8 = -20
    tv_9 = -20
    tv_10 = -20
    tv_11 = -20
    tv_12 = -20
    tv_13 = -20
    tv_14 = -20
    tv_15 = -20
    
    
    if ts_1 == 1:
        tv_1 = read_temp_1()
    if ts_2 == 1:
        tv_2 = read_temp_2()
    if ts_3 == 1:
        tv_3 = read_temp_3()
    if ts_4 == 1:
        tv_4 = read_temp_4()
    if ts_5 == 1:
        tv_5 = read_temp_5()
    if ts_6 == 1:
        tv_6 = read_temp_6()
    if ts_7 == 1:
        tv_7 = read_temp_7()
    if ts_8 == 1:
        tv_8 = read_temp_8()
    if ts_9 == 1:
        tv_9 = read_temp_9()
    if ts_10 == 1:
        tv_10 = read_temp_10()
    if ts_11 == 1:
        tv_11 = read_temp_11()
    if ts_12 == 1:
        tv_12 = read_temp_12()
    if ts_13 == 1:
        tv_13 = read_temp_13()
    if ts_14 == 1:
        tv_14 = read_temp_14()
    if ts_15 == 1:
        tv_15 = read_temp_15()
    
#    print (time.strftime("%I:%M"))
#    print (tv_6)
#    print (tv_14)
#    print (tv_3)
#    print (tv_1)

    
    try:
        con = mdb.connect('localhost',
                        'XXXXXXXX',
                        'XXXXXXXX',
                        'temperature');
        cur = con.cursor()
        cur.execute("INSERT INTO templog(hw, ACi, ACri, poolw, ACko, ACdro, ACoi, ACoo, wall, ACro, poola, roof, gar, pat, fe) VALUES(%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)",(tv_1, tv_2, tv_3, tv_4, tv_5, tv_6, tv_7, tv_8, tv_9, tv_10, tv_11, tv_12, tv_13, tv_14, tv_15))
        #cur.execute("INSERT INTO templog(hw) VALUES(%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s,)",(tv_1, tv_2, tv_3, tv_4, tv_5, tv_6, tv_7, tv_8, tv_9, tv_10, tv_11, tv_12, tv_13, tv_14, tv_15))

        con.commit()
        

    except mdb.Error as e:
        con.rollback()
        print
        "Error %d: %s" % (e.args[0], e.args[1])
        
    finally:
        if con:
            con.close()
    time.sleep(900)

User avatar
DougieLawson
Posts: 35801
Joined: Sun Jun 16, 2013 11:19 pm
Location: Basingstoke, UK
Contact: Website Twitter

Re: Running python script on startup

Fri Dec 22, 2017 7:05 pm

Here's my version

Code: Select all

import mysql.connector as mdb
import sys
import time


try:
    con = mdb.connect(host='localhost', user='pi', password='MySQLPW', db='tester', connection_timeout=1000)
except (mdb.Error, mdb.Warning) as e:
    print(e)
    sys.exit(-1)

sensors=[
  ["28-0000066066dd", 1, "Hot Water"],
  ["28-000006600ffd", 1, "AC Inlet Passage"],
  ["28-0316529e61ff", 1, "AC Roof Xchange Inlet"],
  ["28-800000276014", 0, "Pool"],
  ["28-0416556147ff", 1, "AC Kitchen Outlet"],
  ["28-041655fdf1ff", 1, "AC Day Room Outlet"],
  ["28-041655fdc6ff", 1, "AC Outside Unit Fan Inlet"],
  ["28-0000066143fb", 1, "AC Outside Unit Fan Outlet"],
  ["28-0316526975ff", 1, "Wall Cavity"],
  ["28-041655e0f6ff", 1, "AC Roof Xchange Outlet"],
  ["28-000006616388", 1, "Pool Area Ambient"],
  ["28-031652f316ff", 1, "Roof"],
  ["28-0416557a76ff", 0, "Garage"],
  ["28-041655f892ff", 0, "Patio"],
  ["28-031652f44fff", 0, "Entrance"]
]

def temp_raw(sensor):

    temp_sensor = '/sys/bus/w1/devices/'+sensor+'/w1_slave'
    f = open(temp_sensor, 'r')
    lines = f.readlines()
    f.close()
    return lines
def read_temp(sensor):
    lines = temp_raw(sensor)
    while lines[0].strip()[-3:] != 'YES':
        time.sleep(0.2)
        lines = temp_raw(sensor)
    temp_output = lines[1].find('t=')
    if temp_output != -1:
        temp_string = lines[1].strip()[temp_output+2:]
        temp = round(float(temp_string) / 1000.0,1)
    return temp

while True:

    tv = []

    for t_sensor in sensors:
        sensor = t_sensor[0]
        if t_sensor[1]:
            tv.append(str(read_temp(sensor)))
        else:
            tv.append("NULL")

    try:
        cur = con.cursor()
        cur.execute("INSERT INTO templog(hw, ACi, ACri, poolw, ACko, ACdro, ACoi, ACoo, wall, ACro, poola, roof, gar, pat, fe) VALUES(%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)",(tv))

        con.commit()

    except mdb.Error as e:
        con.rollback()
        print "Error %d: %s" % (e.args[0], e.args[1])

    finally:
        if con:
            con.close()

    time.sleep(900)
    try:
        con = mdb.connect(host='localhost', user='pi', password='MySQLPW', db='tester', connection_timeout=1000)
    except (mdb.Error, mdb.Warning) as e:
        print(e)
        sys.exit(-1)

If starts by importing the new mysql.connector (which is a replacement for MySQLdb) and creating a connection.

First thing is that I've created a python array with the sensor W1 file names, a flag whether they're active or not and a label.

Second I define the function to read the sensors once and once only.

Third I read the array, check the flag (active or not) then write the results into a temporary array.

The temporary array is passed to the SQL exec to update the database.

At the bottom of the loop after the fifteen minute delay I renew the MySQL connection (as it will have timed out).

I've got rid of all of your exceedingly ugly cut'n'paste code (that's why we have functions in python). If you add a new sensor, all you need to do is add a single new line to the sensors = [...] array and a matching new column in your database.
Note: Having anything humorous in your signature is completely banned on this forum. Wear a tin-foil hat and you'll get a ban.

Any DMs sent on Twitter will be answered next month.

This is a doctor free zone.

Geeman2000
Posts: 34
Joined: Mon Jun 15, 2015 7:17 am

Re: Running python script on startup

Fri Dec 22, 2017 10:59 pm

Thanks again for your help.
I'm time poor over the next four days but after I should get a chance to try it out and report back.


cheers
Geeman

meyer.jason
Posts: 5
Joined: Mon Mar 12, 2018 10:37 pm

Re: Running python script on startup

Tue Mar 13, 2018 3:36 pm

Hello I am seeming to get the same error but can't seem to figure out why. The code is a simple pinball game.

Thanks

Service

Code: Select all

[Unit]
Description=Get IMS service running at boot

[Service]
ExecStart=/home/pi/python/pin6.py
Restart=always
StandardOutput=syslog
StandardError=syslog
SyslogIdentifier=IMS
User=pi
Group=pi

[Install]
WantedBy=multi-user.target
Error:

Code: Select all

^[email protected]:/etc/systemd/system $ systemctl status IMS.service
● IMS.service - Get IMS service running at boot
   Loaded: loaded (/etc/systemd/system/IMS.service; enabled; vendor preset: enabled)
   Active: failed (Result: exit-code) since Mon 2018-03-12 16:03:53 PDT; 16h ago
  Process: 311 ExecStart=/home/pi/python/pin6.py (code=exited, status=203/EXEC)
 Main PID: 311 (code=exited, status=203/EXEC)

Mar 12 16:03:53 raspberrypi systemd[1]: IMS.service: Failed with result 'exit-code'.
Mar 12 16:03:53 raspberrypi systemd[1]: IMS.service: Service hold-off time over, scheduling restart.
Mar 12 16:03:53 raspberrypi systemd[1]: Stopped Get IMS service running at boot.
Mar 12 16:03:53 raspberrypi systemd[1]: IMS.service: Start request repeated too quickly.
Mar 12 16:03:53 raspberrypi systemd[1]: Failed to start Get IMS service running at boot.
Mar 12 16:03:53 raspberrypi systemd[1]: IMS.service: Unit entered failed state.
Mar 12 16:03:53 raspberrypi systemd[1]: IMS.service: Failed with result 'exit-code'.
Code

Code: Select all

# External module imports
import os
import RPi.GPIO as GPIO
import time
import math
from time import sleep, strftime
from datetime import datetime
import pickle
import socket
import Adafruit_CharLCD as LCD

# Pin Definitons:
ledPin1 = 2  
ledPin2 = 3
ledBuzz = 4
ledErr	= 17

BallPin = 14
WinPin  = 15
NoBalls = 27

lcd_rs        = 23
lcd_en        = 24
lcd_d4        = 9
lcd_d5        = 11
lcd_d6        = 25
lcd_d7        = 8



TCP_IP = '192.168.1.95'
TCP_PORT 		= 50005
BUFFER_SIZE 	= 1024

# Define LCD column and row size for 16x2 LCD.
lcd_columns 	= 16
lcd_rows    	= 2
lcd_backlight 	= 4

# Initialize the LCD using the pins above.
lcd = LCD.Adafruit_CharLCD(lcd_rs, lcd_en, lcd_d4, lcd_d5, lcd_d6, lcd_d7, lcd_columns, lcd_rows, lcd_backlight)
						   
gBals = 0
gWins = 0
gLast = "time"

# Pin Setup:
GPIO.setmode(GPIO.BCM) # Broadcom pin-numbering scheme
#GPIO.setmode(GPIO.BOARD) # Broadcom pin-numbering scheme

GPIO.setup(ledPin1, GPIO.OUT) # LED pin set as output
GPIO.setup(ledPin2, GPIO.OUT) # LED pin set as output
GPIO.setup(ledBuzz, GPIO.OUT) # LED pin set as output
GPIO.setup(ledErr, GPIO.OUT) # LED pin set as output

GPIO.setup(BallPin, GPIO.IN, pull_up_down=GPIO.PUD_UP) # Button pin set as input w/ pull-up
GPIO.setup(WinPin, GPIO.IN, pull_up_down=GPIO.PUD_UP) # Button pin set as input w/ pull-up
GPIO.setup(NoBalls, GPIO.IN, pull_up_down=GPIO.PUD_UP) # Button pin set as input w/ pull-up
#GPIO.setup(TestLed, GPIO.IN, pull_up_down=GPIO.PUD_UP) # Button pin set as input w/ pull-up
#GPIO.setup(TestLed, GPIO.IN)

# Initial state for LEDs:
GPIO.output(ledPin1, GPIO.LOW)
GPIO.output(ledPin2, GPIO.LOW)
GPIO.output(ledBuzz, GPIO.LOW)
GPIO.output(ledErr, GPIO.LOW)

def FistBoot():
	global gBals
	global gWins
	global gLast
	pickle.dump((gBals,gWins,gLast), open("/home/pi/python/Data2.pickle","wt"))
	#pickling_on.close()

def SaveData():
	global gBals
	global gWins
	global gLast
	cLCD()
	pickle.dump((gBals,gWins,gLast), open("/home/pi/python/Data2.pickle","wt"))
	#pickling_on.close()

def ReadData():
	global gBals
	global gWins
	global gLast
	gBals,gWins,gLast = pickle.load(open("/home/pi/python/Data2.pickle", "rb"))
	print("Read Balls: %d" % gBals)
	print("Read Wins: %d" % gWins)
	print("Last Win: %s" % gLast)
	cLCD()

def fnTCP (Msg):
	s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
	try:
		s.connect((TCP_IP, TCP_PORT))
		s.send(Msg)
		s.close()
	finally:
		s.close()

def cLCD():
	lcd.home()
	lcd.message('Ply:{0} Wins:{1}'.format(gBals,gWins))
	lcd.set_cursor(0,1)
	lcd.message('Last:{0}'.format(gLast))

		
def Winner():
	global gWins
	global gLast
	gWins += 1
	Blink()
	gLast = datetime.now().strftime('%b%d %H:%M\n')
	#os.system('mpg123 -q /home/pi/python/Winnin.mp3 &')
	print("Winner Winner!!")
	print('Played:{0} Wins:{1}'.format(gBals, gWins))
	print('LastWin:{0}'.format(gLast))
	#fnTCP('Played Balls:{0} Wins:{1}\r'.format(gBals, gWins))
	SaveData()

def BallCt():
	global gBals
	gBals += 1
	print("New Ball: %d" % gBals)
	SaveData()

def Blink():
	print('Blinky')
	for x in range(0, 10): 
		GPIO.output(ledPin1, GPIO.HIGH)
		GPIO.output(ledPin2, GPIO.HIGH)
		GPIO.output(ledBuzz, GPIO.HIGH)
		time.sleep(0.1)
		GPIO.output(ledPin1, GPIO.LOW)
		GPIO.output(ledPin2, GPIO.LOW)
		GPIO.output(ledBuzz, GPIO.LOW)
		time.sleep(0.1)

def TestAudio():
	os.system('mpg123 -q vader.mp3 &')

	
print("Here we go! Press CTRL+C to exit")

try:
    ReadData()
except (OSError, IOError) as e:
    #pickle.dump((gBals,gWins), open("Data.pickle", "wb"))
	pickle.dump((gBals,gWins, gLast), open("/home/pi/python/Data2.pickle", "wb"))
	print("Error Reading File")

try:
	while True:
		if (GPIO.input(WinPin) == False):
			Winner()
	 
		if (GPIO.input(BallPin) == False):
			BallCt()
		
		GPIO.output(ledErr, not GPIO.input(NoBalls))
			
		sleep(0.2);
except KeyboardInterrupt: # If CTRL+C is pressed, exit cleanly:
	lcd.clear()
	lcd.set_backlight(0)
	GPIO.cleanup() # cleanup all GPIO


User avatar
DougieLawson
Posts: 35801
Joined: Sun Jun 16, 2013 11:19 pm
Location: Basingstoke, UK
Contact: Website Twitter

Re: Running python script on startup

Tue Mar 13, 2018 6:42 pm

Code: Select all

(code=exited, status=203/EXEC)
You need to determine why your python program is barfing with that 203 exit code.
Note: Having anything humorous in your signature is completely banned on this forum. Wear a tin-foil hat and you'll get a ban.

Any DMs sent on Twitter will be answered next month.

This is a doctor free zone.

meyer.jason
Posts: 5
Joined: Mon Mar 12, 2018 10:37 pm

Re: Running python script on startup

Tue Mar 13, 2018 11:26 pm

So is the code spitting that out or the service file? Cause I can run the python from any folder and it runs fine. I just can't get it to auto start.

Thanks for your help in advance.

User avatar
DougieLawson
Posts: 35801
Joined: Sun Jun 16, 2013 11:19 pm
Location: Basingstoke, UK
Contact: Website Twitter

Re: Running python script on startup

Tue Mar 13, 2018 11:32 pm

You should see the stack trace in /var/log/syslog.
Note: Having anything humorous in your signature is completely banned on this forum. Wear a tin-foil hat and you'll get a ban.

Any DMs sent on Twitter will be answered next month.

This is a doctor free zone.

meyer.jason
Posts: 5
Joined: Mon Mar 12, 2018 10:37 pm

Re: Running python script on startup

Wed Mar 14, 2018 3:22 am

I am not sure, I have tried a bunch of things, I checked all permisions and they seem fine, I even moved the file but no luck.

-rwxr-xr-x 1 pi pi 3967 Mar 13 08:24 pin6.py

Code: Select all

Mar 13 20:04:10 raspberrypi systemd[1]: apt-daily.timer: Adding 11h 52min 3.845493s random time.
Mar 13 20:04:17 raspberrypi systemd[1]: Started Get IMS service running at boot.
Mar 13 20:04:17 raspberrypi systemd[831]: IMS.service: Failed at step EXEC spawning /home/pi/python/pin6.py: Exec format error
Mar 13 20:04:17 raspberrypi systemd[1]: IMS.service: Main process exited, code=exited, status=203/EXEC
Mar 13 20:04:17 raspberrypi systemd[1]: IMS.service: Unit entered failed state.
Mar 13 20:04:17 raspberrypi systemd[1]: IMS.service: Failed with result 'exit-code'.
Mar 13 20:04:17 raspberrypi systemd[1]: IMS.service: Service hold-off time over, scheduling restart.
Mar 13 20:04:17 raspberrypi systemd[1]: Stopped Get IMS service running at boot.

meyer.jason
Posts: 5
Joined: Mon Mar 12, 2018 10:37 pm

Re: Running python script on startup

Wed Mar 14, 2018 3:24 am

I figured it out!!! But have a question.

in your demo service sript you just had the file, in the one I got working I had to add the location of python.

yours:
ExecStart=/home/pi/sample.py

Fix:
ExecStart=/usr/bin/python /home/pi/sample.py

User avatar
rpdom
Posts: 14992
Joined: Sun May 06, 2012 5:17 am
Location: Chelmsford, Essex, UK

Re: Running python script on startup

Wed Mar 14, 2018 5:35 am

Do you have a correct #! line at the start of your script? Without that it won't be automatically recognised as a python script.

meyer.jason
Posts: 5
Joined: Mon Mar 12, 2018 10:37 pm

Re: Running python script on startup

Wed Mar 14, 2018 1:35 pm

That could be it, I must have deleted it.

Return to “Beginners”