nosleep 'till Brooklyn

Fletch on 2003-09-08T15:16:25

Or at least until that long running wget completes. This will temporarily set the OS X energy saver sleep timer to `never', run the specified command, and then restore the sleep time.

#!/usr/bin/perl
##
## nosleep -- Disable sleep while command runs (OS X)
##
use warnings;
use strict;

my @pm_set_cmd = qw( pmset sleep );

unshift @pm_set_cmd, 'sudo' unless $> == 0; ## Setting needs root privs

## Figure out what sleep's set to
my $old_sleep = undef;

open( GET, "pmset -g live |" ) or die "Can't open pipe from pmset -g: $!\n";

while(  ) {
  if( /sleep\s+(\d+)/ ) {
    $old_sleep = $1;
    last;
  }
}

close( GET );

die "Couldn't determine current sleep setting.\n" unless defined $old_sleep;

my $ret;

## Set sleep to 0 (never)
$ret = system( @pm_set_cmd, 0 );
die "Problem setting sleep: @{[ $? >> 8 ]}\n" unless $ret == 0;

## Run command passed as argument
$ret = system( @ARGV );
warn "Problem running command: @{[ $? >> 8 ]}\n" unless $ret == 0;

## Revert to old sleep value
$ret = system( @pm_set_cmd, $old_sleep );
die "Problem setting sleep: @{[ $? >> 8 ]}\n" unless $ret == 0;

exit 0;

__END__
You may wish to add something along these lines to your /etc/sudoers:

Cmnd_Alias      PMSET = /usr/bin/pmset sleep [0-9]*
%admin  ALL=(ALL) ALL, NOPASSWD: PMSET


My laziness demands...

merlyn on 2003-09-08T18:27:02

Replace all of
## Figure out what sleep's set to
my $old_sleep = undef;

open( GET, "pmset -g live |" ) or die "Can't open pipe from pmset -g: $!\n";

while( <GET> ) {
  if( /sleep\s+(\d+)/ ) {
    $old_sleep = $1;
    last;
  }
}

close( GET );
with
my $old_sleep = `pmset -g live` =~ /sleep\s+(\d+)/;

Re:My laziness demands...

danboo on 2003-09-12T18:03:34

I think that should be:
my ($old_sleep) = `pmset -g live` =~ /sleep\s+(\d+)/;

Re:My laziness demands...

merlyn on 2003-09-13T14:12:30

Oh, the irony, since that's nearly the same mistake I ridiculed in my column on "context". {sigh}