脚本在终端中运行良好,但在 launchd 中运行不正常

script runs fine in terminal but not from launchd

我的 Python 脚本 运行 在终端中很好,但是当我尝试将它设置为 运行 每天一次在特定时间启动时(使用软件设置)称为 Lingon),我只是无法将其添加到 运行。从我读过的所有内容来看,最好从 shell 脚本调用 Python 脚本(我在 Macbook 上,运行ning Yosemite)。所以,这就是我想要做的。当脚本是 运行 时我得到的错误是:

未设置 TERM 环境变量。

env: python3: 没有那个文件或目录

在这一点上,我很确定这是一个环境问题,但无论我尝试什么,我都无法达到 运行。顺便说一句,我可以通过这种方式将 shell 脚本按计划发送到 运行:

#!/bin/bash
echo "hello world."

当我尝试 运行 时出现问题:

#!/bin/bash
/Users/jeff/Documents/scripts/my_script.py

另外,虽然我已经用了很长时间的电脑,但我对很多东西还是很无知,所以请告诉我如何解决这个问题,就像我是一个新手一样。

根据文章 here,您需要为 launchd 创建一个 .plist,如下所示:

<?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>Label</key>
    <!-- The label should be the same as the filename without the extension -->
    <string>org.yourusername.my_script-test</string>
    <!-- Specify how to run your program here -->
    <key>ProgramArguments</key>
    <array>
        <string>/usr/local/bin/python3</string>
        <string>/Users/jeff/Documents/scripts/my_script.py</string>
    </array>
    <!-- Run every hour -->
    <key>StartInterval</key>
    <integer>3600</integer><!-- seconds -->
</dict>
</plist>

然后:

$ launchctl load ~/Library/org.yourusername.my_script-test.plist
$ launchctl start org.yourusername.my_script-test

这里有一篇文章涵盖了environment variables

我已经尝试了所有提到的方法,特别感谢 Padraic,但似乎没有任何效果。这很奇怪,因为当从终端 运行 时脚本 运行 是完美的,但当从启动 运行 时出现错误。当从 launchd 运行 时,我能够消除错误,但是脚本不会从终端 运行 。很奇怪。但这是我如何在终端和按计划从启动时将其设置为 运行。首先,我更改了 shebang 行:

#!/usr/bin/env python3

对此:

#!/usr/bin/env /Library/Frameworks/Python.framework/Versions/3.4/bin/python3.4

然后我必须在脚本的其余部分指定文件的完整路径,例如,来自:

log = open('log_directory/my_log.log', 'a')

对此:

log = open('/Users/jeff/documents/my_script_documents/python/development/log_directory/my_log.log', 'a')

无论如何,现在一切正常,但我相信我遇到的问题可能与将我的 Mac 升级到 Yosemite OS 有关。有一些关于 Yosemite 中关于 launchd/launchd.conf/launchctl 的可能错误的提及。好吧,我想相信在过去的 4 天里不是我试图让它工作......但谁知道呢?