简体   繁体   English

Python脚本从crontab失败

[英]Python script failing from crontab

I've gone through multiple threads, but I still can't seem to find my problem. 我已经经历了多个线程,但似乎仍然找不到我的问题。

I'm building a really simple Twitter bot that I'd like to fire every hour, on the hour with a cron job from a Raspberry Pi. 我正在构建一个非常简单的Twitter机器人,我想每小时从Raspberry Pi上执行cron工作,以每小时触发一次。 Here's my crontab: 这是我的crontab:

PYTHONPATH=/usr/bin/python
MAILTO=*myemail*
00 * * * * /home/username/directory/my_script.py >> /var/log/cron.log

Then the script: 然后脚本:

#! /usr/bin/env python
import sys
from twython import Twython, TwythonError
from pymarkovchain import MarkovChain

#TWITTER ACCESS
apiKey = KEY
apiSecret = SECRET
accessToken = TOKEN
accessKey = KEY

#text to pull
text = open('/home/username/directory/text.txt').read()

#Generate database and frequency table
mc = MarkovChain('/home/username/directory/markov')
mc.generateDatabase(text)
tweet = mc.generateString()

api = Twython(apiKey,apiSecret,accessToken,accessKey)

try:
    api.update_status(status=tweet)
except TwythonError as e:
    print e

The first thing I checked was all of my referenced files to make sure they were absolute references. 我检查的第一件事是所有引用的文件,以确保它们是绝对引用。 Then, I checked to make sure my file paths were correct. 然后,我检查以确保文件路径正确。 I'm really stumped here. 我真的很在这里 Running the script from command line with the full path works as expected. 从命令行使用完整路径运行脚本可以正常工作。 Any thoughts are appreciated. 任何想法表示赞赏。

After trying the suggestions above and reading countless articles, I learned that cron has to run as root, not as the user. 在尝试了以上建议并阅读了无数文章之后,我了解到cron必须以root用户而不是用户身份运行。 I checked the logs and saw that the user calling the script was the owner of the file, not root. 我检查了日志,发现调用脚本的用户是文件的所有者,而不是root。 So, running chmod a+x my_script.py took care of it. 因此,运行chmod a+x my_script.py可以解决此问题。

Thanks for all the suggestions - especially those getting the errors to the correct log file. 感谢所有建议-尤其是那些将错误保存到正确的日志文件中的建议。

To debug better, you might want to redirect stderr: 为了更好地调试,您可能需要重定向stderr:

00 * * * * /home/username/directory/my_script.py >> /tmp/cron.log 2>&1
# or
00 * * * * /home/username/directory/my_script.py >> /tmp/cron.log 2>/tmp/cron-error.log

(I also changed the path there to make sure your cron user has permission to write output.) (我还更改了那里的路径,以确保您的cron用户有权写入输出。)

Another thing you could try is run the script with Python in cron: 您可以尝试的另一件事是在cron中使用Python运行脚本:

00 * * * * python /home/username/directory/my_script.py >> /tmp/cron.log 2>&1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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