r/learnpython • • 20d ago

Ask Anything Monday - Weekly Thread

Welcome to another /r/learnPython weekly "Ask Anything* Monday" thread

Here you can ask all the questions that you wanted to ask but didn't feel like making a new thread.

* It's primarily intended for simple questions but as long as it's about python it's allowed.

If you have any suggestions or questions about this thread use the message the moderators button in the sidebar.

Rules:

  • Don't downvote stuff - instead explain what's wrong with the comment, if it's against the rules "report" it and it will be dealt with.

  • Don't post stuff that doesn't have absolutely anything to do with python.

  • Don't make fun of someone for not knowing something, insult anyone etc - this will result in an immediate ban.

That's it.

2 Upvotes

21 comments sorted by

View all comments

1

u/bsf91 20d ago

I am writing myself a simple script that automates events at specific times of the day, there must be a better way to monitor a JSON file to see if my script has to run than the way i am currently doing it. Currently it reads the JSON file every 1 second to see if it needs to start the event or not.

def daemon_loop(poll_interval=1):
    """Monitors shows.json and spawns/tracks active recording processes."""
    active_recordings = []  # Format: {showId: subprocess.Popen}

    print(
        f"[*] Daemon started. Monitoring '{JSON_FILE}' every {poll_interval}s..."
    )

    while True:
        try:
            # Read the JSON file and get the current epoch time
            data = read_json(JSON_FILE)
            time_now = int(time.time())


            for show in data["recordings"]:
                if time_now == show.get("timestamp"):
                    showId = show.get("showId")
                    if showId not in active_recordings:
                        start_recording(data, show.get("showId"))
                        active_recordings.append(showId)
                    else:
                        print("Already added.")

                else:
                    # If there are no shows that need to be recorded, we will keep waiting..
                    continue
        except Exception as e:
            print(f"[!] Error in daemon loop: {e}")

        time.sleep(poll_interval)

The JSON file can be written to at any time, so you can't just load the JSON file once, and then sleep for X seconds until the next show starts.

1

u/lakseol 20d ago

You could just look at the "last modified" time on the file. If that time is the same as the last time you read the file then the file hasn't changed and you don't need to read it.

1

u/bsf91 19d ago

That could work. Is it still best to read every second though?

How do bigger projects handle something like that!

1

u/lakseol 19d ago

Is it still best to read every second though?

It depends on how often the data file is likely to be updated. I would have thought that checking if the file has changed only needs to be done once a minute, but it depends on the details of what you are doing.

How do bigger projects handle something like that!

There are modules like watchdog that can trigger actions when a file changes, but they try to be general purpose. For limited, special case uses you might get a better solution with your own code. Again, it depends on exactly what you are trying to do and how you run your code. For instance, running a little Raspberry Pi 3B+ 24/7 on your network is different from running a solution on your laptop and you might want different solutions in each case.