4

I'm on a Mac and I'd like to be able to sleep my computer from a python script. I can do it in bash with this command:

/System/Library/CoreServices/Menu\ Extras/User.menu/Contents/Resources/CGSession -suspend

I read the instructions on this post and followed the instructions, but I ran into the following error.

import subprocess    
subprocess.Popen("/System/Library/CoreServices/Menu\ Extras/User.menu/Contents/Resources/CGSession -suspend")

FileNotFoundError: [Errno 2] No such file or directory: '/System/Library/CoreServices/Menu\ Extras/User.menu/Contents/Resources/CGSession -suspend': '/System/Library/CoreServices/Menu\ Extras/User.menu/Contents/Resources/CGSession -suspend'

0asa
  • 224
  • 1
  • 8
Cauder
  • 2,157
  • 4
  • 30
  • 69

1 Answers1

4

Try:

import subprocess    
subprocess.run(["/System/Library/CoreServices/Menu Extras/User.menu/Contents/Resources/CGSession",
                "-suspend"])

You have to provide an existing path without escapes required by the shell (so "Menu\ Extras" -> "Menu Extras") as the first parameter, and pass the other parameters separately.

Nickolay
  • 31,095
  • 13
  • 107
  • 185
  • 1
    for more complicated commands shlex is nice. `subprocess.run(shlex.split("/System/Library/CoreServices/Menu Extras/User.menu/Contents/Resources/CGSession -suspend"))` – Grady Player Aug 12 '19 at 03:42