在Mac开机时运行Python脚本
我想让一个Python脚本在开机时自动运行。我有一个文件:com.test.service.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.test.service</string>
<key>ProgramArguments</key>
<array>
<string>/bin/sh</string>
<string>/var/www/html/app/appstart.sh</string>
</array>
<key>RunAtLoad</key>
<true/>
</dict>
</plist>
这个文件被复制到了 ~/Library/LaunchAgents/ 目录下。
然后被加载为
launchctl load -w ~/Library/LaunchAgents/com.test.service.plist
这个脚本有两行代码:
/usr/bin/python /var/www/html/app/app.py
echo "hello" >> /var/www/html/app/test.txt
这个脚本可以运行(会创建一个名为 test.txt 的文件,里面写着'hello'),但是 app.py 并没有运行。为了测试,我在 app.py 里只做了以下操作:
import os
os.system("echo 'python' >> /var/www/html/app/test.txt")
如果我在终端直接运行 appstart.sh,Python 就能正常运行。
我已经按照 这个问题里的说明操作过了,但还是没有成功。
2 个回答
1
确保 .plist 文件的权限设置为 644。
你提到的“在 Mac 启动时运行”和“开机时运行”,这让我觉得你可能在错误的目录里。LaunchAgents 是用来在用户登录时运行脚本的。如果你想在开机时运行,.plist 文件需要放在 /Library/LaunchDaemons 目录下,并且要归 root:wheel 用户所有。
如果你不需要通过一个 shell 来启动一个 shell 脚本再去启动 Python,那我建议你使用一个快捷方式:
<key>ProgramArguments</key>
<array>
<string>/usr/bin/python</string>
<string>/var/www/html/app/app.py</string>
</array>
1
之前我用过cron来实现这个功能。你可以这样添加一个条目:
@reboot /path/to/my/script
这里的“/path/to/my/script”就是你自己的appstart.sh文件的路径。
首先,你需要打开终端。
然后输入 crontab -e
(这会在你默认的编辑器中打开一个文件,可能是nano)。
接着,往下滚动到文件的底部,输入 @reboot /path/to/file
最后,保存并退出这个文件。