Score:0

Ubuntu Struggling to run Python Script on Startup

in flag

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.

EODCraft Staff avatar
cn flag
Is there any error reported in the Log? Please append to post.
user535733 avatar
cn flag
I see "print" statements in your scripts. Since systemd runs headless, those won't be printed to the screen. Consider writing your output to a file instead, then use any of several tools to read that output once you are logged in.
Score:1
in flag

I have found a solution to the problem. I found out you can activate the virtual environment for the project and then start the program inside of the virtual environment.

In the project, the venv can by activated via [project_path]/venv/bin/python

Here are the changes for the solution:

[Unit]
Description=Python Internet Watcher
After=network-online.target

[Service]
WorkingDirectory=/home/connor/Documents/Pycharm
ExecStart=/home/connor/Documents/Pycharm/venv/bin/python internettracker.py start
Restart=always
RestartSec=15s
KillMode=process
TimeoutSec=infinity
User=connor
Group=connor

[Install]
WantedBy=multi-user.target

command-line python

bac0n avatar
cn flag
The working directory of a .service is the same as the system root directory `/` in which the service manager started, and `~` for user .service units.
mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.