r/pythonhelp • • Nov 09 '20

Shutdown MacOS with Python script?

Hi. I'm very new to Python and don't know much about it. I created a script to mess with my friend and I don't know how to get it to work. I want to make it so that the Mac shuts down after the countdown but it doesn't seem to be working. Here's the code.

import time

import subprocess

shutdown = input("Do you wish to go on an epic adventure? (y/n) ")

if shutdown == 'no':

print('\nYour loss, pal.')

exit()

else:

seconds = 3

print('Alright! You ready?')

for i in range(seconds):

print(str(seconds - i)

time.sleep(2):

subprocess.call(['osascript', '-e',

'tell app "System Events" to shut down'])

Any help would be useful. Thanks.

3 Upvotes

1 comment sorted by

1

u/Mayor-Hotdog Nov 09 '20 edited Nov 09 '20

Hi, I am also new to python. I think I got your script to work, I don't have a mac so I can't test it to see if it will shutdown but from my short google, it should work. I would suggest that you try to get the script to allow other versions of no such as 'No' 'no' 'N' 'n' just so when they type let's say 'n' as that is what it is asking for it won't shutdown, but this is your script and if it is meant to be that way then forget I said anything. Anyways, here is the script, if you have any questions about the script or need more help, feel free to ask.

- - - - -

import time

import subprocess

shutdown = input("Do you wish to go on an epic adventure? (y/n) ")

if shutdown == 'no':

print("\\nYour loss, pal.")

exit()

else:

seconds = 321

print("Alright! You ready?")

for i in str(seconds):

	print(i)

	time.sleep(2)

subprocess.run('shutdown -h now')

- - - - -

Hope this helps.

*edit - I have never done anything with the subprocess module so you might need to do some tweaking but I am positive that the rest works.