如何在 MAC OS 10.8.5 上使用正确的文件权限运行 plist 守护程序

如何在 MAC OS 10.8.5 上使用正确的文件权限运行 plist 守护程序

我有一个 plist 文件保存到

/Library/LaunchDaemons/local.WiFiDaemon.plist

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertropertyList-1.0.dtd">
<plist version="1.0">
<dict>
        <key>Disabled</key>
        <false/>
        <key>GroupName</key>
        <string>staff</string>
        <key>InitGroups</key>
        <true/>
        <key>Label</key>
        <string>local.job</string>
        <key>ProgramArguments</key>
        <array>
                <string>python</string>
                <string>/Library/Application Support/PythonDaemons/PythonTest.py</string>
        </array>
        <key>RunAtLoad</key>
        <true/>
        <key>StandardErrorPath</key>
        <string>/tmp/local.job.err</string>
        <key>StandardOutPath</key>
        <string>/tmp/local.job.out</string>
        <key>UserName</key>
        <string>myuser</string>
</dict>
</plist>

该文件用于执行一个 Python 脚本,该脚本仅 ping google 并将结果保存到文本文件中:

/Library/Application Support/PythonDaemons/Ping_log.txt

问题是 Python 脚本给出错误,说它没有该文件的权限。当我从命令行运行脚本时,一切都运行正常,不需要任何特殊权限。我在这里错过了什么?

以下是 Python 脚本:

import subprocess, datetime, time

host = "www.google.com"
ping = subprocess.Popen(
                        ["ping", "-c", "4", host],
                        stdout = subprocess.PIPE,
                        stderr = subprocess.PIPE)
out, error = ping.communicate()
with open('PingOut.txt', 'w') as outFile:
    outFile.write(out)
temp = out.split('\n')
parsed = temp[len(temp)-2].split('/')
min = parsed[len(parsed)-4].split(' ')[2]
avg = parsed[len(parsed)-3]
max = parsed[len(parsed)-2]

print "min: " + str(min) + "avg: " + str(avg) + "max: " + str(max)

with open('Ping_log.txt', 'a') as f:
 f.write(str(datetime.datetime.now()) + ',' + str(min) + ',' + str(avg) + ',' + str(max))

答案1

我通过 stackoverflow 得到了答案,显然没有在 python 文件中定义路径,而只是提供文件名,它默认在系统目录中创建文件,而我无权访问这些文件。解决方案是:在 python 中设置工作路径

with open('/Library/Application Support/PythonDaemons/Ping_log.txt', 'a') as f:

或者在 plist 中设置目录

<key>WorkingDirectory</key>
<string>/Library/Application Support/PythonDaemons</string>

这是 StackOverflow 上的用户 Barmar 提供的

相关内容