【问题标题】:running a python script on Mac boot在 Mac 启动时运行 python 脚本
【发布时间】:2014-03-12 16:58:25
【问题描述】:

我正在尝试让 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

脚本有 2 行:

/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 运行没有问题

我已经按照this question 中的说明进行操作,但没有运气

【问题讨论】:

  • 为什么你的 app.py 脚本和 bash 脚本做同样的事情?
  • 因为我不想在这里粘贴 200 行代码,这是测试脚本是否运行的一种非常快速简单的方法。

标签: python macos boot launchd


【解决方案1】:

前段时间我使用 cron 来做这件事。你可以这样输入

@reboot /path/to/my/script

more info about cron

我的脚本的路径将是您的 appstart.sh 文件的路径。

所以你打开你的终端。

你输入crontab -e(这将在你的默认编辑器中打开一个文件,可能是nano)

向下滚动并在文件底部键入@reboot /path/to/file

然后保存并退出。

【讨论】:

  • 我在苹果网站上知道他们建议不要使用 cron,但它似乎是 OS X 上唯一可靠的任务调度程序。感谢您的回答。
【解决方案2】:

确保 .plist 文件是 chmod 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>

【讨论】:

  • 在我的情况下实际上并不重要,在用户登录时运行也可以,但这些都不适合我
猜你喜欢
  • 2018-08-29
  • 2013-02-16
  • 2014-08-22
  • 1970-01-01
  • 1970-01-01
  • 2020-04-01
  • 1970-01-01
  • 2023-02-24
  • 2018-11-07
相关资源
最近更新 更多