【问题标题】:How to run a Python command in a .plist?如何在 .plist 中运行 Python 命令?
【发布时间】:2016-04-19 17:43:50
【问题描述】:

我想添加一个运行 Python 文件的 LaunchDaemon。有没有简单的方法可以做到这一点?

【问题讨论】:

标签: python macos daemon launchd


【解决方案1】:

选项 1

显式启动python解释器:

<?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>RunAtLoad</key>
    <true/>
    <key>Label</key>
    <string>tld.yourdomain.YourService</string>
    <key>ProgramArguments</key>
    <array>
        <string>/usr/bin/python</string>
        <string>/path/to/your/script.py</script>
    </array>
    <key>UserName</key>
    <string>root</string>
</dict>
</plist>

选项 2

  • 使您的 python 脚本可执行 (chmod +x /path/to/your/script.py)
  • 在第一行打个“她”(#!/usr/bin/python#!/usr/bin/env python

然后直接运行你的脚本

<?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>RunAtLoad</key>
    <true/>
    <key>Label</key>
    <string>tld.yourdomain.YourService</string>
    <key>ProgramArguments</key>
    <array>
        <string>/path/to/your/script.py</script>
    </array>
    <key>UserName</key>
    <string>root</string>
</dict>
</plist>

我应该说RunAtLoad = true 不是推荐的开始工作方式。真的只有在没有其他办法的情况下才这样做。如果您想手动运行它,只需放下它并执行launchctl start tld.yourdomain.YourService。加载服务launchctl load /path/to/the/plist.plist 或将其粘贴在/Library/LaunchAgents/Library/LaunchDaemons~/Library/LaunchAgents 中。

并且:UserName = root 只有在它是 LaunchDaemon 时才可能。如果您不需要它,也可以去掉它并使其成为 LaunchAgent(每个用户一个实例,而不是整个系统一个实例)。

【讨论】:

    猜你喜欢
    • 2021-08-30
    • 1970-01-01
    • 2014-06-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-02
    • 1970-01-01
    相关资源
    最近更新 更多