Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/env python
- import time
- import os
- import sys
- import platform
- from datetime import datetime as dt
- from datetime import timedelta
- from dateutil.relativedelta import relativedelta
- #a dictionary is far neater and more verbose than using a long conditional block
- shutdown_cmds = {"Windows" : "shutdown -s -f -t 0", "Linux" : "systemctl poweroff",
- "Darwin" : "osascript -e 'tell app \"System Events\" to shut down'",
- "Windows reboot" : "shutdown -r -f -t 0", "Linux reboot" : "systemctl reboot",
- "Darwin reboot" : "osascript -e 'tell app \"System Events\" to restart'"}
- #now let's write a function that return the exact name of the os (portability)
- def getOS():
- os_list = ["Windows", "Linux", "Darwin"]
- os_name = platform.system()
- for item in os_list:
- if item in os_name:
- return item
- #display a pretty countdown
- def count_down(future):
- #relative delta takes 2 datetime objects, beginning and end, and returns
- #the difference between them
- diff = relativedelta(dt.now(), future)
- hours = abs(diff.hours)
- mins = abs(diff.minutes)
- secs = abs(diff.seconds)
- return "\r%d hours, %d mins %d seconds left..." % (hours, mins, secs)
- #next we need to add a given time string (hours or minutes or seconds or all)
- #to datetime.now() to create the destination datetime object
- def makeDest(time_str):
- #dictionaries are freaking awesome!
- time_dict = {"hours" : 0, "mins" : 0, "seconds" : 0}
- for unit in time_str.split(" "):
- unit = unit.lower()
- if "h" in unit:
- time_dict["hours"] = int(unit[:-1])
- elif "m" in unit:
- time_dict["mins"] = int(unit[:-1])
- else:
- if "s" in unit:
- unit = unit[:-1]
- time_dict["seconds"] = int(unit)
- return dt.now() + timedelta(hours=time_dict["hours"], minutes=time_dict["mins"],
- seconds=time_dict["seconds"])
- #almost finished! let's write the main function
- def main(reboot=False):
- #prompt the user for a time string
- time_str = input("\nPlease enter the countdown duration in seconds, or enter it like this 1h 2m 3s (you don't have to enter more than one): ")
- target = makeDest(time_str)#destination time
- os_task = getOS()#get the name of the os we're running on
- if reboot:
- os_task += " reboot"
- print("Countdown initiated... Press ctrl + c any time to abort...")
- while True:#a while loop is needed to display the countdown to the user
- try:
- diff = target - dt.now()#it is possible to subtract datetime objects
- sys.stdout.write(count_down(target))
- time.sleep(1)
- sys.stdout.flush()
- if diff.total_seconds() <= 0:#break out of the loop when the destination is reached
- break
- except KeyboardInterrupt:
- sys.exit("\nCanceled by user ._.")#give the user the choice to abort
- break
- os.system(shutdown_cmds[os_task])#execute the os specific shutdown command.. did I mention that dicts are awesome?!
- if __name__ == "__main__":
- print("\nBrought to you by Monro Coury...\n\n")
- if input("Would you like to (s)hutdown or (r)eboot? ").lower() in ("r", "reboot"):
- main(reboot=True)
- else:
- main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement