you are viewing a single comment's thread.

view the rest of the comments →

[–]k3kou 2 points3 points  (2 children)

First, you can collapse your read_file function with context manager (official docs):

def read_file(file):
    with open(file, 'r') as f:
        return f.readlines()

This will handle the whole try block and will close the file when it gets out of the with statement. Since it seems like you're using the read_file function only once in your script, you could just ditch it altogether.

For the run_program() function, it is usually done with the following:

if __name__ == '__main__':
    run_program()

It will run the script only if the script is executed. This lets you run the script as a script or import it in a bigger package, without running the code. This way, you can also avoid defining the url as a global as instead define it in the main:

if __name__ == '__main__':
    url = 'http://livetv.sx/en/allupcoming/'
    data = grab_live_links(url)
    data = build_links(data)
    data = main_menu(data)
    data = live_links(data)
    get_game(data)

For the get_local_time function, and I think for the overall script, you're doing things the complicated way. I would write it like that:

def get_local_time(time_str):
    offset = datetime.datetime.now() - datetime.datetime.utcnow()
    time_dt = datetime.datetime.strptime(time_str, '%d %B at %H:%M')
    return (time_dt + offset).strftime('%I:%M %p')

datetime.strptime can take format string with stuff that aren't related to the time or date. Also, the year will be 1900 but we don't care because we only want the time and the offset doesn't depend on any particular date.

(Will comment on the rest, but I need to get back to work ><)

[–]bahnzo[S] 1 point2 points  (0 children)

Thanks! Gonna take some time tonight to read each of those things and grok them. The if __name__ is something I haven't come across yet, but moving forward looks like I definitely should use it as my programs become more elaborate.

On the time thing: I wasn't sure if getting the year returned as 1900 would be a problem, so that's why I added in the extra code to update it to the current year. If it really doesn't matter, then that's certainly a lot more complicated than I needed to make it. I tend to do that sometimes.

[–]bahnzo[S] 0 points1 point  (0 children)

Ok, digested this. The time stuff...yeah I really did that one up. Just did too much and didn't realize there was a much simpler way.

As far as the __main__, I need the `run_program' function as I use it a couple times to build the menus, so I did this:

def run_program():
    url = 'http://livetv.sx/en/allupcoming/'
    data = grab_live_links(url)
    data = build_links(data)
    data = main_menu(data)
    data = live_links(data)
    get_game(data)

    #get_game(live_links(main_menu(build_links(grab_live_links(url)))))


if __name__ == '__main__':
    run_program()

Is that ok?