2

I have a Python script that I would like to run on a Mac at system start up in a detached screen session.

The Python File (foo.py):

import time
import datetime

while True:
    print 'hello', datetime.datetime.now()
    time.sleep(2)

The Shell Script Which Calls It (run_foo.sh):

#!/bin/bash
username=`whoami`
_python=`which python`
screen -dm -S run_foo $_python /Users/$username/foo.py

The Plist Which Calls The Shell Script: https://gist.github.com/cooncesean/6617008

===========

The Python script runs fine on its own:

> python foo.py
hello 2013-09-18 21:20:22.132170
hello 2013-09-18 21:20:24.133420
hello 2013-09-18 21:20:26.134697
...

The Shell script that calls the Python script runs fine on its own:

> sh run_foo.sh
There is a screen on:
1922.run_foo    (Detached)
1 Socket in /var/folders/4z/0413fcs523l8nz12xbvng0bh0000gn/T/.screen.

> screen -r run_foo
hello 2013-09-18 21:24:57.243103
hello 2013-09-18 21:24:59.244349

Loading the plist (which calls the shell script, which creates the screen and runs the Python script) leaves me with a dead screen session that needs to be wiped.

> launchctl load ~/Library/LaunchAgents/start-foo.plist

> screen -list
There is a screen on:
1951.run_foo    (Dead ???)
Remove dead screens with 'screen -wipe'.
1 Socket in /var/folders/4z/0413fcs523l8nz12xbvng0bh0000gn/T/.screen.

UPDATE: It appears launchd does not allow you to call a daemon (in this case, screen) and raises an exception. So, how does one start a screen session at startup on a Mac? crontab?

0

I was able to get this working by piecing together a few different answers [1][2][3].

I made a script to launch my screen command as follows:

#!/usr/bin/env bash
screen -dmS MySessionName $SHELL
screen -S MySessionName -p 0 -X stuff "myprogram"$'\n'

then saved this as a .sh file, and ran chmod a+x on it. In Finder, I used Cmd-I to set Terminal.app as the default way to open .sh type files. Then simply go to System Preferences->Users and Accounts->Login Items, click + and add the file.

References:

  1. https://askubuntu.com/a/983176/667707
  2. https://superuser.com/a/307486/691289
  3. https://superuser.com/a/995564/691289

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.