Advertisement
MonroCoury

shutdown

Jan 19th, 2018
144
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 3.34 KB | None | 0 0
  1. #!/usr/bin/env python
  2. import time
  3. import os
  4. import sys
  5. import platform
  6. from datetime import datetime as dt
  7. from datetime import timedelta
  8. from dateutil.relativedelta import relativedelta
  9.  
  10.  
  11. #a dictionary is far neater and more verbose than using a long conditional block
  12. shutdown_cmds = {"Windows" : "shutdown -s -f -t 0", "Linux" : "systemctl poweroff",
  13.                  "Darwin" : "osascript -e 'tell app \"System Events\" to shut down'",
  14.                  "Windows reboot" : "shutdown -r -f -t 0", "Linux reboot" : "systemctl reboot",
  15.                  "Darwin reboot" : "osascript -e 'tell app \"System Events\" to restart'"}
  16.  
  17.  
  18. #now let's write a function that return the exact name of the os (portability)
  19. def getOS():
  20.     os_list = ["Windows", "Linux", "Darwin"]
  21.     os_name = platform.system()
  22.     for item in os_list:
  23.         if item in os_name:
  24.             return item
  25.  
  26.  
  27. #display a pretty countdown
  28. def count_down(future):
  29.     #relative delta takes 2 datetime objects, beginning and end, and returns
  30.     #the difference between them
  31.     diff = relativedelta(dt.now(), future)
  32.     hours = abs(diff.hours)
  33.     mins = abs(diff.minutes)
  34.     secs = abs(diff.seconds)
  35.     return "\r%d hours, %d mins %d seconds left..." % (hours, mins, secs)
  36.  
  37.  
  38. #next we need to add a given time string (hours or minutes or seconds or all)
  39. #to datetime.now() to create the destination datetime object
  40. def makeDest(time_str):
  41.     #dictionaries are freaking awesome!
  42.     time_dict = {"hours" : 0, "mins" : 0, "seconds" : 0}
  43.     for unit in time_str.split(" "):
  44.         unit = unit.lower()
  45.         if "h" in unit:
  46.             time_dict["hours"] = int(unit[:-1])
  47.         elif "m" in unit:
  48.             time_dict["mins"] = int(unit[:-1])
  49.         else:
  50.             if "s" in unit:
  51.                 unit = unit[:-1]
  52.             time_dict["seconds"] = int(unit)
  53.     return dt.now() + timedelta(hours=time_dict["hours"], minutes=time_dict["mins"],
  54.                                 seconds=time_dict["seconds"])
  55.  
  56.  
  57. #almost finished! let's write the main function
  58. def main(reboot=False):
  59.     #prompt the user for a time string
  60.     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): ")
  61.     target = makeDest(time_str)#destination time
  62.     os_task = getOS()#get the name of the os we're running on
  63.     if reboot:
  64.         os_task += " reboot"
  65.  
  66.     print("Countdown initiated... Press ctrl + c any time to abort...")
  67.     while True:#a while loop is needed to display the countdown to the user
  68.         try:
  69.             diff = target - dt.now()#it is possible to subtract datetime objects
  70.  
  71.             sys.stdout.write(count_down(target))
  72.             time.sleep(1)
  73.             sys.stdout.flush()
  74.  
  75.             if diff.total_seconds() <= 0:#break out of the loop when the destination is reached
  76.                 break
  77.  
  78.         except KeyboardInterrupt:
  79.             sys.exit("\nCanceled by user ._.")#give the user the choice to abort
  80.             break
  81.     os.system(shutdown_cmds[os_task])#execute the os specific shutdown command.. did I mention that dicts are awesome?!
  82.  
  83. if __name__ == "__main__":
  84.     print("\nBrought to you by Monro Coury...\n\n")
  85.     if input("Would you like to (s)hutdown or (r)eboot? ").lower() in ("r", "reboot"):
  86.         main(reboot=True)
  87.     else:
  88.         main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement