Crontab问题,即使我在目录中有文件也说"没有这样的文件或目录"

时间:2016-11-26 14:41:30

标签: python crontab

即使我在目录中有文件说"没有这样的文件或目录"我该如何解决这个问题?

我使用crontab -e添加了crontab。

crontab的;

MAILTO="" 
*/1 * * * * /home/TwitterFollowBot/bot.py 2>/tmp/twitterBot.log

Bot.py

#!/usr/bin/env python

from TwitterFollowBot import TwitterBot
my_bot = TwitterBot()

from TwitterFollowBot import TwitterBot
my_bot = TwitterBot("config.txt")  

from TwitterFollowBot import TwitterBot   
my_bot = TwitterBot()
my_bot.sync_follows()

from TwitterFollowBot import TwitterBot    
my_bot = TwitterBot()
my_bot.auto_rt("@ShoutGamers", count=2200)

径;

/home/TwitterFollowBot/bot.py

Crontab日志;

Traceback (most recent call last):
  File "/home/TwitterFollowBot/bot.py", line 5, in <module>
    my_bot = TwitterBot()
  File "/home/TwitterFollowBot/TwitterFollowBot/__init__.py", line 42, in __init__
    self.bot_setup(config_file)
  File "/home/TwitterFollowBot/TwitterFollowBot/__init__.py", line 78, in bot_setup
    with open(config_file, "r") as in_file:
IOError: [Errno 2] No such file or directory: 'config.txt'

1 个答案:

答案 0 :(得分:0)

Crontab不会在其所在的目录中运行您的代码,因为它只运行您从其配置的任何位置(可能是您的主目录)放入的命令。

您可以通过sys.argv获取文件的路径来解决此问题:

#!/usr/bin/env python

import sys
import os.path
from TwitterFollowBot import TwitterBot

path = sys.argv[0].rsplit("/", 1)[0]

TwitterBot()  # I don't know if this does something, but as the assigned value is never used...

TwitterBot(os.path.join(path, "config.txt"))  # Same here. I put the path in front of "config.txt"

TwitterBot().sync_follows()

TwitterBot().auto_rt("@ShoutGamers", count=2200)