I'm trying to run two scripts in a python project on startup in Ubuntu but it keeps having issues.
I have a Python project like the following:
- pycharm
- venv
- date.txt
- globalfunctions.py
- internet.txt
- internetdate.txt
- internettimelog.txt
- internettracker.py
- poweroutages.txt
- poweroutagetracker.py
- timelog.txt
The project path is /home/connor/Documents/Pycharm, with the IDE being a virtual environment of Python 3.8.10
And the two files I am trying to run are the internettracker.py and poweroutagetracker.py. The two codes are the following:
internettracker.py
import requests
import time
import globalfunctions as gf
url = "http://www.kite.com"
timeout = 5
def ping_internet():
try:
request = requests.get(url, timeout=timeout)
return True
except (requests.ConnectionError, requests.Timeout) as exception:
return False
gf.log_today(additional="internet")
while True:
internet_connected = ping_internet()
if internet_connected:
datestring, timenumber = gf.get_log(additional="internet")
curtime, today = gf.get_today()
if abs(curtime - timenumber) > 35:
gf.report_data("internet.txt", "Internet outage from [" + datestring + "] to [" + str(today) + "]")
print("Internet Outage Detected")
gf.log_today(additional="internet")
time.sleep(30)
else:
time.sleep(15)
poweroutagetracker.py
import time
from datetime import datetime
import globalfunctions as gf
while True:
datestring, timenumber = gf.get_log()
curtime, today = gf.get_today()
if abs(curtime - timenumber) > 5:
gf.report_data("poweroutages.txt", "Power outage from [" + datestring + "] to [" + str(today) + "]")
print("Power Outage Detected")
time.sleep(5)
gf.log_today()
Supporting file with functions
globalfunctions.py
import time
from datetime import datetime
def get_today():
return time.time(), datetime.today()
def log_today(additional=""):
curtime, today = get_today()
datefile = open(additional+"date.txt", "w")
datefile.write(str(today))
datefile.close()
timefile = open(additional+"timelog.txt", "w")
timefile.write(str(curtime))
timefile.close()
def get_log(additional=""):
datefile = open(additional+"date.txt", "r")
datestring = datefile.readline()
timefile = open(additional+"timelog.txt", "r")
timenumber = float(timefile.readline())
return datestring, timenumber
def report_data(filename, text):
curtime, today = get_today()
outfile = open(filename, "a+")
outfile.write(str(today) + " | " + text + "\n")
outfile.close()
I tried following the instructions from this thread but it does not seem to be working.
I made a .service with the following:
[Unit]
Description=Python Internet Watcher
[Service]
Type=simple
WorkingDirectory=/home/connor/Documents/Pycharm
ExecStart=./internettracker.py
[Install]
WantedBy=multi-user.target
This file was moved into /lib/systemd/system/ and so far I saw nothing being ran on startup.