我在云上运行Ubuntu 16.04.3 LTS。当我使用Rscript从命令行运行程序时,一切都按预期进行。但是,当我通过cron使用Rscript运行相同的程序时,似乎没有调用我的.Rprofile文件。我已经写了一个小程序来演示这个问题:
test_cron = function() {
#The next 3 lines are base R.
sink('~/test_cron.out')
on.exit(sink())
cat('The date and time are:', as.character(Sys.time()), '\n')
#Now try to access a personal option, set by .Rprofile.
root = getOption('root')
cat('Option root:', root, '\n')
}
test_cron()我从命令行使用以下命令运行此命令:
Rscript test_cron.rcron_test.out文件包含以下内容:
The date and time are: 2017-11-14 06:15:46
Option root: /home/ubuntu/_algi/crontab中的相关行如下:
20 6 * * * /usr/bin/Rscript ~/test_cron.r当它由cron运行时,cron_test.out包含以下内容:
The date and time are: 2017-11-14 06:20:01
Option root:显然,当该程序由cron运行时,无法访问我的个人选项“root”。这是我做过的一系列实验中的一个,这些实验让我相信.Rprofile不是在cron下调用的。有什么办法可以解决这个问题吗?
注意: R_PROFILE_USER环境变量被设置为指向我的.Rprofile文件。显然,cron下的Rscript忽略了它。
发布于 2017-11-14 16:00:20
默认情况下,R按特定顺序在以下三个位置查找并运行.Rprofile文件:
主工作目录:R为installed
的目录
您当前项目/wd中的.Rprofile将覆盖HOME中的.Rprofile,HOME中的R_HOME和.Rprofile将覆盖R_HOME。
因此,要创建特定于项目的启动脚本,只需在项目的根目录中创建一个.Rprofile文件。
在您的例子中,当通过cron启动脚本时,R使用不同的.Rprofile文件,而不是从命令行启动脚本。
发布于 2017-11-15 09:20:16
它表明cron不会加载用户的环境。这造成了无尽的困惑和痛苦,没有普遍接受的解决方案。例如,请参见
https://serverfault.com/questions/673480/load-users-environment-variables-in-a-cronjob
https://stackoverflow.com/questions/15557777/cron-job-does-not-get-the-environment-variables-set-in-bashrc
https://stackoverflow.com/questions/2229825/where-can-i-set-environment-variables-that-crontab-will-use
https://unix.stackexchange.com/questions/27289/how-can-i-run-a-cron-command-with-existing-environmental-variables一个密切相关的问题是,.bashrc只能在交互式外壳中运行::
https://unix.stackexchange.com/questions/257571/why-does-bashrc-check-whether-the-current-shell-is-interactive我的解决方案是编写一个shell脚本,在其中设置必要的环境变量,然后运行我的程序:
#!/bin/bash
export CODE_HOME='/home/ubuntu/'
export OS='Ubuntu'
export R_PROFILE_USER=~/R/.Rprofile
/usr/bin/Rscript ~/test_cron.r在使脚本成为可执行文件之后,它将在crontab下成功运行。
https://stackoverflow.com/questions/47279009
复制相似问题