Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
some logic help
#1
Question 
I have a UPS, and once in a while, the driver crashes for some unknown reason. It needs to be (re)started using this command: upsdrvctl start. I've written a python3 script to attempt to automatically monitor the relevant log (/var/log/syslog), and when it detects certain text, such as "Driver not connected" or "Data stale" at the end of the file, it will issue that command. That commands takes about 15s to run completely.
When I run it as is, it picks up on those error messages. Then issues the command. Then new log entries from the system (not relevant to any of this) are entered. Yet it still thinks the driver is in a bad state.
I am never good with loops, especially loops within loops. I also don't script much, so I'm sure it's messy, can be refactored, etc. Just looking to get the job done. :) I am all for simplifying the logic and learning, though!

import time
import subprocess

while True:
    with open('/var/log/syslog') as f:
        # Get the last line of the log file
        for line in f:
            pass
        last_line = line.rstrip()
        print(last_line)
        # Wait some time for a new log entry to be entered
        print("Sleeping for 30s...\n")
        time.sleep(30)

        # Now check if the new last line of the file matches what it did before
        # If it does not, check to see if the driver has failed
        for new_line in f:
            new_line = new_line.rstrip()
            if new_line == last_line:
                # No new entries
                pass
            else:
                # We have new log entries.  Check for driver errors.
                if 'Driver not connected' in new_line or 'Data stale' in new_line:
                    bash_command = "upsdrvctl start"
                    process = subprocess.Popen(bash_command.split(), stdout=subprocess.PIPE)
                    output, error = process.communicate()
                    print(f'Output: {output} \nError: {error}')
                    print("[!] Restarting driver... Please wait...")
                    time.sleep(30)
                    print("[!] Driver has been restarted!\n")
Reply


Messages In This Thread
some logic help - by droidus - Jun-10-2023, 05:34 PM
RE: some logic help - by deanhystad - Jun-10-2023, 08:53 PM
RE: some logic help - by droidus - Jun-10-2023, 11:34 PM
RE: some logic help - by deanhystad - Jun-11-2023, 07:55 AM
RE: some logic help - by Gribouillis - Jun-11-2023, 09:28 AM
RE: some logic help - by droidus - Jun-11-2023, 10:41 AM

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020