macospython-3.xsystem-shutdown

Computer Shut Off Python 3.4


A friend of mine wants to automatically shut off his computer using Python 3.4 (to put in a program). Does anyone know a basic as-small-as-possible way to do this?

OS: Mac OSX Yosemite

Thanks


Solution

  • OS X is a Unix at its base, so you can use Unix commands. you can use either:

    #!/usr/bin/python
    import os
    os.system("shutdown -h now")
    

    Must be run as root, won't work otherwise. You can however add to sudoers (man visudo) shutdown as NOPASSWD program for the users that want to execute the script and use sudo shutdown … instead of just shutdown…

    or

    import subprocess
    subprocess.call(['osascript', '-e',
    'tell app "System Events" to shut down'])