r/madeinpython • • May 05 '20

Made in python: a folder clock

Post image
25 Upvotes

7 comments sorted by

View all comments

2

u/its-a-unix-system- May 05 '20

Link: https://github.com/antonio-gor/folder-clock

I prefer to hide my dock and status bar but hate moving my cursor to the top to view the time. Enter, a tiny stupid folder-clock.

1

u/SnowdenIsALegend May 06 '20

Amazing stuff! Great idea! Can you share a video of the final product? I would love to see it in action.

1

u/robin-gvx May 06 '20

If you appreciate feedback:

  • It might make more sense to use os.rename instead of a combination of os.rmdir and os.mkdir

  • You store some state on your FolderClock instance that is only used in one place (time and period). It would make more sense to simply use them as return values instead.

  • The method h24_to_h12 is not used anywhere.

  • You don't need to format the time, then parse the result of that only to format it yet again. Additionally, you don't need to pass time.localtime() to time.strftime, as it is the default value. You can replace all of get_time and some of update with time.strftime("%I.%M %p" if self.mode == 12 else "%H.%M")

  • argparse.ArgumentParser.add_argument can be given a type parameter to do automatic type conversion. It also takes default and choices

  • mode should only take the values 12 or 24. To me, it makes more sense to use a boolean with a descriptive name instead of an integer.

  • You can make use of pathlib.Path, which simplifies your code a bit.

  • If the user quits the program, the clock directory sticks around. The program should probably clean up after itself. In this case you can use a bare except and simply reraise the original exception inside of run.

Putting it all together:

"""  folder_clock.py
The tiny stupid folder-clock you never asked for.

Example:
    Run in your current working directory in 12h mode:
        $ python folder_clock.py
    Run in a specified directory (ie, Desktop):
        $ python folder_clock.py --wd ~/Desktop
    Run in 24h mode:
        $ python folder_clock --mode 24
    Run in a specified directory in 24h mode
        $ python folder_clock.py --wd ~/Desktop --mode 24
"""
import argparse
from pathlib import Path
from datetime import datetime, timedelta
import time
import os

ONE_MINUTE = timedelta(minutes=1)

class FolderClock:
    '''Folder clock class'''
    def __init__(self, parent_directory, use_24_hour_clock):
        self.parent_directory = parent_directory
        self.use_24_hour_clock = use_24_hour_clock
        self.previous = None

    def run(self):
        '''Start displaying the folder clock'''
        try:
            while True:
                self.update()
                now = datetime.now()
                delta = 60 - datetime.datetime.now().second
                time.sleep(delta)  # Sleep until minute changes
        except:
            if self.previous:
                self.previous.rmdir()
            raise

    def update(self):
        '''Create a folder with the time as its name'''
        new_directory_name = time.strftime("%H.%M" if self.use_24_hour_clock else "%I.%M %p")
        if self.previous:
            self.move_folder(new_directory_name)
        else:
            self.make_folder(new_directory_name)

    def make_folder(self, dir_name):
        '''Create folder'''
        self.previous = self.parent_directory / dir_name
        try:
            self.previous.mkdir()
        except OSError:
            print(f"Creation of the directory {self.previous} failed")

    def move_folder(self, dir_name):
        '''Rename the previously created folder'''
        try:
            self.previous = self.previous.rename(dir_name)
        except OSError:
            print(f"Moving directory {self.previous} to {dir_name} failed")


def get_args():
    '''Get system args for wd and mode'''
    parser = argparse.ArgumentParser()
    parser.add_argument("--wd", help="dir to display the folder-clock [default: the current working directory]", default='', type=Path)
    parser.add_argument("--mode", type=int, help="either 12 or 24 hr mode [default: 12]", default=12, choices=[12, 24])
    args = parser.parse_args()
    return args.wd, args.mode == 24

def main():
    '''Run the clock'''
    fc = FolderClock(*get_args())
    fc.run()

if __name__ == '__main__':
    main()

2

u/its-a-unix-system- May 07 '20

Whoa! Thanks for going through all of that! I’ll make sure to incorporate everything you said. I appreciate it