Zlo February 2016

Start Python scripts with launchctl (OSX)

I have a very simple test scrip that I want my computer to run every 60 seconds - time_test_script.py. The script simply saves a .txt file with current time as name and writes some text onto the file. The file is in /Users/me/Documents/Python dir.

import datetime
import os.path
path = '/Users/me/Desktop/test_dir'
name_of_file = '%s' %datetime.datetime.now()
completeName = os.path.join(path, name_of_file+".txt")
file1 = open(completeName, "w")
toFile = 'test'
file1.write(toFile)
file1.close()
print datetime.datetime.now()

I also have a .plist file – test.plist that is in /Library/LaunchAgents dir.

test.plist

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>Label</key>
    <string>com.test</string>
    <key>ProgramArguments</key>
    <array>
        <string>/Users/me/Documents/Python/time_test_script.py</string>
    </array>
    <key>StartInterval</key>
    <integer>60</integer>
</dict>
</plist>

If I run the script manually it works fine, i.e. is creates a .txt file in the specified directory. However, when I try to initiate launchctl from the Terminal nothing happens.

 $ launchctl load /Library/LaunchAgents/test.plist 
 $ launchctl start com.test

What am I doing wrong?

Answers


Zoe O'Connell February 2016

If you are running a script without using python scriptname.py, then the script needs to be marked executable (chmod a+x scriptname.py from the command line) and the first line should tell the system which interpreter to use, which in this case will be #!/usr/bin/python.

For example:

Sapphist:~ zoe$ cat >test.py
print "Hello World"
Sapphist:~ zoe$ ./test.py
-bash: ./test.py: Permission denied

With just the execute bit set:

Sapphist:~ zoe$ cat >test.py
print "Hello World"

Sapphist:~ zoe$ chmod a+x test.py
Sapphist:~ zoe$ ./test.py
./test.py: line 1: print: command not found

With both an interpreter and execute bit:

Sapphist:~ zoe$ cat >test.py
#!/usr/bin/python
print "Hello World!"

Sapphist:~ zoe$ chmod a+x test.py
Sapphist:~ zoe$ ./test.py
Hello World!
Sapphist:~ zoe$

Post Status

Asked in February 2016
Viewed 3,941 times
Voted 10
Answered 1 times

Search




Leave an answer