Skip to content
The Chat Archive
gpt-4o-mini-2024-07-18· OpenAI WildChat-4.8M (AI2)

Improve next code and make it more professional: #!/usr/bin/python3 import os import sys…

  1. User

    Improve next code and make it more professional: #!/usr/bin/python3 import os import sys import subprocess import random

    if len(sys.argv) < 2: print("You forgot path to wallpaper directory as argument!") sys.exit()

    def get_monitor_name(): try: result = subprocess.run(['hyprctl', 'monitors'], capture_output=True, text=True, check=True) lines = result.stdout.splitlines()

        for line in lines:
            if 'Monitor' in line:
                monitor_name = line.split()[1]
                return monitor_name
        return None
    except subprocess.CalledProcessError as e:
        print(f"Error executing command: {e}")
        return None
    

    directory = sys.argv[1] monitor = get_monitor_name()

    if monitor == None: sys.exit()

    if os.path.isdir(directory): random_background = random.choice(os.listdir(directory)) subprocess.run(["hyprctl", "hyprpaper", "unload", "all"]) subprocess.run(["hyprctl", "hyprpaper", "preload", sys.argv[1] + "/" + random_background]) subprocess.run(["hyprctl", "hyprpaper", "wallpaper", f"{monitor}, {sys.argv[1] + '/' + random_background}"]) else: print(f"Directory {directory} does not exist") sys.exit()

  2. Assistant

    Certainly! Below is an improved version of your Python script. I've added comments for clarity, organized the imports, handled exceptions more robustly, and improved the overall structure and readability.

    #!/usr/bin/env python3
    
    import os
    import sys
    import subprocess
    import random
    
    def get_monitor_name():
        """Retrieves the monitor name using the 'hyprctl' command."""
        try:
            result = subprocess.run(['hyprctl', 'monitors'], capture_output=True, text=True, check=True)
            for line in result.stdout.splitlines():
                if 'Monitor' in line:
                    return line.split()[1]  # Return the monitor name
        except subprocess.CalledProcessError as e:
            print(f"Error executing 'hyprctl': {e}")
        return None  # Return None if no monitor found or if an error occurred
    
    def set_wallpaper(directory, monitor):
        """Sets a random wallpaper from the specified directory on the given monitor."""
        if not os.path.isdir(directory):
            print(f"Error: Directory '{directory}' does not exist.")
            sys.exit(1)  # Exit with error status if directory doesn't exist
        
        try:
            # Choose a random image file from the directory
            random_background = random.choice(os.listdir(directory))
            wallpaper_path = os.path.join(directory, random_background)
    
            # Unload existing wallpapers and set the new one
            subprocess.run(["hyprctl", "hyprpaper", "unload", "all"], check=True)
            subprocess.run(["hyprctl", "hyprpaper", "preload", wallpaper_path], check=True)
            subprocess.run(["hyprctl", "hyprpaper", "wallpaper", f"{monitor}, {wallpaper_path}"], check=True)
            print(f"Successfully set wallpaper to: {wallpaper_path}")
        except Exception as e:
            print(f"Error while setting wallpaper: {e}")
    
    def main():
        if len(sys.argv) != 2:
            print("Usage: python3 set_wallpaper.py <path_to_wallpaper_directory>")
            sys.exit(1)
    
        directory = sys.argv[1]
        monitor = get_monitor_name()
    
        if monitor is None:
            print("No monitor found. Ensure that Hyprland is running with monitors attached.")
            sys.exit(1)
    
        set_wallpaper(directory, monitor)
    
    if __name__ == "__main__":
        main()
    

    Improvements Made:

    1. Function Modularity: The code is refactored into functions for better readability and maintainability.
    2. Error Handling: Enhanced error handling to ensure graceful exits under different failure scenarios.
    3. Path Handling: Used os.path.join() for constructing file paths, which is more robust across different operating systems.
    4. Param Checking: Improved command-line argument checking with clear usage instructions if arguments are incorrect.
    5. Comments and Documentation: Added comments to clarify the purpose of each function and key steps in the code.
    6. Return Values: Functions now have clear paths and return values for better control flow and debugging.

    This overall structure will help maintain the code in the future and might be preferable in a professional development environment.