每分钟安排一次Rscript crontab

时间:2016-08-04 23:06:37

标签: r terminal cron crontab

由于某种原因,我的R脚本不会与crontab一起运行。我现在每分钟都有它进行测试,但一旦工作就会改变它。

有什么想法吗?

import logging
from collections import namedtuple
logging.basicConfig(level=logging.DEBUG)

# See https://docs.python.org/3/library/collections.html#collections.namedtuple
# but namedtuples are an awesome way to group related
# data that allows you to use attribute lookup.
# In this case - point.x and point.y.
# Point was my best guess for name, since you
# had `x` and `y`.
Point = namedtuple('Point', ('x', 'y'))

# There was no need to pass in any of these values
# Returning lists is better than passing them in to
# be mutated. Also you're not writing to the file in
# here that I see. It'd be better to pass in a file
# object if you need to control that from outside
# the function
def read_columns(filename):
    data = []  # creating a list of data here

    # Better to use logging - that way you can just
    # change the log level if you don't want to see
    # the messages any more
    logging.debug('Reading from file %r', filename)
    try:
        with open(filename) as file:
            for line in file:
                line = line.strip()
                logging.debug('Line: %r', line)

                # Parenthesis aren't necessary
                # `line is not ""` is checking for
                # identity and not equality. Also
                # an empty line will evaluate to False.
                # but iterating over lines will always
                # include the `\n` so we call line.strip()
                # earlier
                if line.strip() and 'X' not in line:
                    left, right = line.split()
                    point = Point(x=float(left), y=float(right))
                    if point.x > 2:
                        data.append()
    except FileNotFoundError as e:
        sys.exit("File {!r} does not exist".format(filename))

    return data

此外,这只是终端中的正常命令。

3 个答案:

答案 0 :(得分:6)

我可以在你的cron条目中看到可怕的smart quotes。当您从文字处理器复制粘贴时,通常会发生这种情况。退回这些可憎的行为并重新输入正常报价。变化:

* * * * * Rscript “/Users/Home/Desktop/David Studios/Scraper/compiler.R”

* * * * * Rscript "/Users/Home/Desktop/David Studios/Scraper/compiler.R"

看到区别?它很微妙,容易错过。

更新

我发现你已经做出了上述改变,但它仍然不适合你。验证Rscript是否属于拥有此crontab的用户的$PATH环境变量。或者,您可以直接在cron条目中指定Rscript的完全限定路径。您可以使用以下命令在命令行上快速找到它:

which Rscript

更新#2:

我在评论中看到Rscript的完全限定路径为/usr/local/bin/Rscript。我猜测/usr/local/bin不在拥有此crontab的用户的路径中。尝试使用完全限定的路径,如下所示:

* * * * * /usr/local/bin/Rscript "/Users/Home/Desktop/David Studios/Scraper/compiler.R"

答案 1 :(得分:2)

检查您是否确实在运行crontab守护进程。您应该获得一个数字作为退货,这是crontab的进程ID。

pgrep cron

确保您的R文件是可执行的:

sudo chmod +x [yourfile.R]

在您的R文件中添加shebang行:

#!/usr/local/bin/Rscript

让crontab更改目录:

* * * * * cd /Users/Home/Desktop/David Studios/Scraper/ && /usr/local/bin/Rscript compiler.R

答案 2 :(得分:1)

您可能对R中的工作目录有疑问。

从终端运行脚本时,您可能位于脚本所需文件所在的目录中,但是当脚本与cron一起运行时,它将使用另一个目录。

在R脚本内使用setwd()函数,或在访问文件时使用绝对路径以确保无论在何处使用该脚本,该脚本都可以工作。