简体   繁体   中英

Python script works in terminal but not with launchd

Im trying to run a python script using launchd on OS X. When I run it from the terminal using the following commands, it works:

$ /Library/Frameworks/Python.framework/Versions/3.4/bin/python3.4 /Users/me/path/to/script.py

Here is my launchd plist file that has those same commands under the ProgramArguments key, but it doesn't work.

<?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>
    <string>net.me.my-script</string>
    <key>ProgramArguments</key>
    <array>
        <string>/Library/Frameworks/Python.framework/Versions/3.4/bin/python3.4</string>
        <string>/Users/me/path/to/script.py</string>
    </array>
    <key>StartInterval</key>
    <integer>86400</integer>
</dict>
</plist>

The launchd initially didnt work, so I tried running it in the terminal manually, and I got an error and realized that I needed to refer to files I was reading and writing to in the python script with their full path, so I fixed that. That made the script run in terminal but it didn't fix the problem in launchd (yes, I've unloaded and loaded it multiple times).

I ran launchctl list and found a 1 exit code listed next to my plist, then I checked /var/log/system.log and found the error message Service exited with abnormal code: 1 but that's all the error messages I can find.

Based on 'last modified' dates and stuff from finder, it seems like it opens an xml file in the python script, but it doesn't write anything to it. It also doesn't seem to open a json file in the script.

Again, all this stuff works just fine run manually in the terminal, so I'm thinking it has to be a plist or launchd issue.

Solved. I was able to set the StandardErrorPath and StandardOutPath keys and see the errors the script was throwing. I was getting a few UnicodeEncodeError s on instances of f.write() and f.read() when manipulating the xml file, but only when running the script through launchd. I replaced with open('file.xml', 'w') as f: with with io.open('file.xml', 'w', encoding='utf8') as f: and the same for the read instances, and it works! Anyone know why this worked fine in my IDE and in terminal but not in launchd?? All using same interpreter.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM