[Python] Reading a file to get a directory from it but the file has more than just the...

Discussão em 'Python' iniciado por Stack, Janeiro 31, 2025.

  1. Stack

    Stack Membro Participativo

    I made a program that's supposed to monitor the world_path.json with watchdog in order to find a directory to events.log, then it monitors it to read keywords from it and then based on that keywords it changes the wallpaper.

    When I run this program it shows the current path to event.log every 5 seconds for debug purposes. So right now it gets stuck on monitoring the latest_world.json and never actually finds the path to events.log even though it detects changes to it. What causes it to not update when it's supposed to?

    import os
    import json
    import tkinter as tk
    from tkinter import filedialog, ttk
    from watchdog.observers import Observer
    from watchdog.events import FileSystemEventHandler
    import ctypes
    import threading
    import time


    def set_wallpaper(image_path):
    print(f"Attempting to change wallpaper: {image_path}")
    if os.path.exists(image_path):
    print(f"Changing wallpaper to: {image_path}")
    ctypes.windll.user32.SystemParametersInfoW(20, 0,
    image_path, 3)
    else:
    print(f"Wallpaper file not found: {image_path}")


    class PaceWallpapersApp:
    def __init__(self, root):
    self.root = root
    self.root.title("Pace Wallpapers")
    self.root.geometry("500x400")

    self.latest_world_path = ""
    self.events_log_path =
    "E:/multimc/MultiMC/instances/Instance 1/.minecraft/events.log"
    self.wallpapers = {i: "" for i in range(8)}

    self.notebook = ttk.Notebook(root)
    self.main_frame = ttk.Frame(self.notebook)
    self.wallpapers_frame = ttk.Frame(self.notebook)

    self.notebook.add(self.main_frame, text="Main")
    self.notebook.add(self.wallpapers_frame, text="Wallpapers")
    self.notebook.pack(expand=True, fill="both")

    ttk.Button(self.main_frame, text="Select latest_world.json",
    command=self.select_latest_world).pack(pady=5)
    ttk.Button(self.main_frame, text="Start Monitoring",
    command=self.start_monitoring).pack(pady=5)
    ttk.Button(self.main_frame, text="Stop Monitoring",
    command=self.stop_monitoring).pack(pady=5)

    self.wallpaper_labels = {}
    for i in range(8):
    frame = ttk.Frame(self.wallpapers_frame)
    frame.pack(pady=2, fill="x")
    btn = ttk.Button(frame, text=f"Select Wallpaper {i}",
    command=lambda n=i: self.select_wallpaper(n))
    btn.pack(side="left")
    lbl = ttk.Label(frame, text="None", width=30)
    lbl.pack(side="left", padx=5)
    self.wallpaper_labels = lbl

    self.observer = Observer()
    self.latest_world_handler = LatestWorldHandler(self)
    self.events_handler = EventsLogHandler(self)

    self.monitor_thread =
    threading.Thread(target=self.monitor_events_log_path,
    daemon=True)
    self.monitor_thread.start()

    def monitor_events_log_path(self):
    while True:
    print(f"Current events.log path:
    {self.events_log_path}")
    time.sleep(5)

    def select_latest_world(self):
    file_path = filedialog.askopenfilename(filetypes=[("JSON
    files", "*.json")])
    if file_path:
    self.latest_world_path = file_path
    print(f"Selected latest_world.json: {file_path}")

    def start_monitoring(self):
    if not self.latest_world_path:
    print("No latest_world.json selected.")
    return
    print("Starting monitoring latest_world.json...")
    self.observer.schedule(self.latest_world_handler,
    os.path.dirname(self.latest_world_path), recursive=False)
    self.observer.start()

    def stop_monitoring(self):
    print("Stopping monitoring...")
    self.observer.stop()
    self.observer.join()
    self.observer = Observer()

    def select_wallpaper(self, index):
    file_path = filedialog.askopenfilename(filetypes=[("Image
    files", "*.jpg;*.png;*.bmp")])
    if file_path:
    self.wallpapers[index] = file_path

    self.wallpaper_labels[index].config(text=os.path.basename
    (file_path) )
    print(f"Selected wallpaper {index}: {file_path}")
    class LatestWorldHandler(FileSystemEventHandler):
    def __init__(self, app):
    self.app = app

    def on_modified(self, event):
    print(f"Detected change in latest_world.json:
    {event.src_path}")
    if event.src_path == self.app.latest_world_path:
    with open(self.app.latest_world_path, "r") as file:
    data = json.load(file)
    world_path = data.get("world_path", "")
    if world_path:
    self.app.events_log_path =
    os.path.join(world_path, "speedrunigt", "events.log")
    print(f"Updated events.log path:
    {self.app.events_log_path}")
    if os.path.exists(self.app.events_log_path):
    print(f"events.log found at:
    {self.app.events_log_path}, monitoring started.")
    else:
    print("Warning: events.log does not exist at
    the expected location!")

    self.app.observer.schedule(self.app.events_handler,
    os.path.dirname(self.app.events_log_path),
    recursive=False)


    class EventsLogHandler(FileSystemEventHandler):
    def __init__(self, app):
    self.app = app

    def on_modified(self, event):
    if event.src_path == self.app.events_log_path:
    print(f"Detected change in events.log:
    {event.src_path}")
    with open(self.app.events_log_path, "r") as file:
    lines = file.readlines()
    for line in reversed(lines):
    for keyword, wallpaper_num in {
    "enter_nether": 1,
    "enter_bastion": 2,
    "enter_fortress": 3,
    "first_portal": 4,
    "enter_stronghold": 5,
    "enter_end": 6,
    "credits": 7,
    "leave_world": 0
    }.items():
    if keyword in line:
    print(f"Detected: {keyword}, new
    wallpapre {wallpaper_num}")

    set_wallpaper(self.app.wallpapers.get(wallpaper_num, ""))
    return


    if __name__ == "__main__":
    root = tk.Tk()
    app = PaceWallpapersApp(root)
    app.start_monitoring()
    root.mainloop()




    self.wallpaper_labels[index].config(text=os.path.basename(file_path) )
    print(f"Selected wallpaper {index}: {file_path}")


    class LatestWorldHandler(FileSystemEventHandler):
    def __init__(self, app):
    self.app = app

    def on_modified(self, event):
    print(f"Detected change in latest_world.json:
    {event.src_path}")
    if event.src_path == self.app.latest_world_path:
    with open(self.app.latest_world_path, "r") as file:
    data = json.load(file)
    world_path = data.get("world_path", "")
    if world_path:
    self.app.events_log_path =
    os.path.join(world_path, "speedrunigt", "events.log")
    print(f"Updated events.log path:
    {self.app.events_log_path}")
    if os.path.exists(self.app.events_log_path):
    print(f"events.log found at:
    {self.app.events_log_path}, monitoring started.")
    else:
    print("Warning: events.log does not exist at
    the expected location!")

    self.app.observer.schedule(self.app.events_handler,
    os.path.dirname(self.app.events_log_path),
    recursive=False)


    class EventsLogHandler(FileSystemEventHandler):
    def __init__(self, app):
    self.app = app

    def on_modified(self, event):
    if event.src_path == self.app.events_log_path:
    print(f"Detected change in events.log:
    {event.src_path}")
    with open(self.app.events_log_path, "r") as file:
    lines = file.readlines()
    for line in reversed(lines):
    for keyword, wallpaper_num in {
    "enter_nether": 1,
    "enter_bastion": 2,
    "enter_fortress": 3,
    "first_portal": 4,
    "enter_stronghold": 5,
    "enter_end": 6,
    "credits": 7,
    "leave_world": 0
    }.items():
    if keyword in line:
    print(f"Detected: {keyword}, new
    wallpapre {wallpaper_num}")

    set_wallpaper(self.app.wallpapers.get(wallpaper_num, ""))
    return


    if __name__ == "__main__":
    root = tk.Tk()
    app = PaceWallpapersApp(root)
    app.start_monitoring()
    root.mainloop()


    The content of the latest_world.json file looks like this:

    {"world_path":"E:/multimc/MultiMC/instances/psesjeisheesse/.minecraft/saves/New sea (11)","mods":["antigone","antiresourcereload","atum","chunkumulator","extra-options","fabricloader","fast_reset","forceport","java","krypton","lazydfu","lazystronghold","lithium","minecraft","mixinextras","sleepbackground","sodium","speedrunigt","standardsettings","starlight","state-output","state-output-common","voyager","worldpreview"],"version":"1.16.1","mod_version":"14.1+1.16.1","category":"ANY"}

    Continue reading...

Compartilhe esta Página