如果要让脚本作为自动启动的守护进程运行,则可以使用launchctl和plist文件。
例如,Bob有一个简单的python脚本,该脚本每秒在其主目录中将单词’foo’写入文件:
#!/usr/bin/env pythonimport osimport timewhile True: os.system('echo " foo" >> /Users/bob/foostore.txt') time.sleep(1)要使其作为守护进程运行,请创建一个plist文件,
~/Library/LaunchAgents/com.bobbob.osx.test.plist其内容为:
<?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>
然后用于
launchctl从终端加载plist:
launchctl load ~/Library/LaunchAgents/com.bobbob.osx.test.plist
这将加载该脚本并立即在
<string>下面的元素中运行程序
<key>Program</key>。您也可以使用
<ProgramArguments>带有
<string>元素数组的节点为程序指定参数。有关更多信息,请参见launchd.plist手册页。
如果要删除脚本,可以使用以下命令的卸载命令
launchctl:
launchctl unload ~/Library/LaunchAgents/com.bobbob.osx.test.plist
脚本中使用的标签可以是任何东西,但在您的系统上应该是唯一的,因此Apple通常使用反向域名。
至于执行脚本的老师,我认为没有任何办法可以做到这一点。



