Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
528 views
in Technique[技术] by (71.8m points)

macos - Running Python in background on OS X

Is there any way to keep my Python script (with an endless 'while' loop) running in the background on OS X? Also, for the same purpose, is there any way to have "autorun" python script on a USB drive?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

If you want to have the script running as a daemon process which starts automatically, you can use launchctl and a plist file.

For example, Bob has a simple python script which writes the word 'foo' to a file every second in his home directory:

#!/usr/bin/env python
import os
import time

while True:
  os.system('echo " foo" >> /Users/bob/foostore.txt')
  time.sleep(1)

To have it run as a daemon process, create a plist file, ~/Library/LaunchAgents/com.bobbob.osx.test.plist, with the contents:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC -//Apple Computer//DTD PLIST 1.0//EN http://www.apple.com/DTDs/PropertyList-1.0.dtd >
<plist version="1.0">
  <dict>
    <key>Label</key>
    <string>com.bobbob.osx.test</string>
    <key>Program</key>
    <string>/Users/bob/pyfoo.py</string>
    <key>KeepAlive</key>
    <true/>
  </dict>
</plist>

Then use launchctl to load the plist from a terminal:

launchctl load ~/Library/LaunchAgents/com.bobbob.osx.test.plist

This will load that script and immediately run the program in the <string> element beneath <key>Program</key>. You can also specify arguments for the program using a <ProgramArguments> node with an array of <string> elements. For more information see the launchd.plist man page

If you want to remove the script, you can use the unload command of launchctl:

launchctl unload ~/Library/LaunchAgents/com.bobbob.osx.test.plist

The Label used in the script can be anything, but it should be unique on your system, so Apple generally uses a reversed domain name.

As for autorunning a script, I don't think there's any way to do that.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...