Skip to content

Instantly share code, notes, and snippets.

@adriangoransson
Created April 22, 2015 20:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save adriangoransson/b7efabcba02328a88ecb to your computer and use it in GitHub Desktop.
Save adriangoransson/b7efabcba02328a88ecb to your computer and use it in GitHub Desktop.
shutdown.py. Python3 required.
import subprocess
import time
import datetime
def main():
# Dictionary with strings that can be input and the methods that they call.
options = {
'H': hibernate,
'S': shutdown,
'X': exit
}
# Initialise action with an empty string value. This is to prevent our
# loop below to check an undefined variable on its first run.
action = ''
prompt = 'Press H for hibernate, S for shutdown. X to cancel: '
# Loop until H, S or X is entered in the promt.
while action not in options:
action = input(prompt).upper()
options[action]()
def hibernate():
# Python has a style guide (PEP8) that enforces a limit of
# 79 characters per line.
# Multiple strings witin parentheses will be concatenated into one.
minutes = getMinutes('In how many minutes should the computer '
'be put in hibernate? ')
seconds = minutes * 60
endTime = getEndOfWaitTime(seconds)
print('Computer will hibernate at {0}'.format(endTime))
# Wait.
time.sleep(seconds)
# Call the OS specific shutdown command.
subprocess.call('shutdown', '/h')
def shutdown():
minutes = getMinutes('In how many minutes should the computer '
'be shut down? ')
seconds = minutes * 60
endTime = getEndOfWaitTime(seconds)
print('Computer will shut down at {0}'.format(endTime))
# Alternatively use the t flag for shutdown command.
time.sleep(seconds)
subprocess.call('shutdown', '/s')
def getMinutes(prompt):
minutes = None
# As long as minutes does not evaluate to true, keep on going.
# Below we cast the string result of input() to an integer.
# Which, if not valid, will be 0 (false). Non zero integers equal true.
while not minutes:
try:
minutes = int(input(prompt))
except ValueError:
minutes = None
return minutes
def getEndOfWaitTime(seconds):
now = time.time()
# Add the amount of seconds passed to the function.
end = now + seconds
endTime = datetime.datetime.fromtimestamp(end)
# Return string formatted as YYYY-MM-DD HH:MM:SS
return endTime.strftime('%Y-%m-%d %H:%M:%S')
# The main function will only be executed if this script was called directly.
# Like $ python3 shutdown.py
# If it was not contained like this then the prompt would run every time you
# import this file.
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment