不得不说,用久了Rstudio 自己果然变笨了。之前竟然用了几天命令行下进入R 反复执行一段脚本,就在那里等着。
稍微总结一下后台执行R 的方法,其实很简单。
就是上面提到的我的笨方法,通过Rserver, ssh…… 连接到服务器,执行命令后:
重开一个连接即可:
另外,我发现如果是使用Rstudio 或juypter lab 这些工具,关闭terminal 后,系统并不会自动帮你将该terminal 下的程序内存清除。
这就导致了我发现,后台出现了非常多状态为S 的R 进程,我不得不手动kill 掉它们。
同样进入R后,命令执行后,我们可以使用ctrl + z ,将程序挂起。
> Sys.sleep(10000000)
^Z
[1]+ Stopped R
接下来使用bg 将程序放到后台继续执行:
$ bg 1
[1]+ R &
$ jobs -l
[1]+ 16366 Running R &
在接触R之间,我是厌恶写代码的。为什么?
因为往往为了得到结果,我不得不写长长的脚本,而可能得到的只有短短的结果。
而遇到R 以后,随便调个参数,掉个函数,我就可以在Rstudio 里自由地驰骋在交互的海洋。
如果是费时的命令呢?
其实就是调用Rscript 执行你写好的R 脚本:
nohup Rscript ./Script/BREMSC.R > bremsc.log 2>&1 &
需要注意的是:
或者你想在后台查看是否是你运行的脚本呢?
而且,你也可以通过jobs 随时查看脚本是否正常运行:
$ jobs -l
[1]- 11445 Running nohup Rscript ./Script/BREMSC.R > bremsc.log 2>&1 &
[2]+ 11560 Running nohup Rscript ./Script/CiteFuse.R > citefuse.log 2>&1 &
既然有了脚本,我们有时候必不可免的需要用到传参来加速我们的代码执行效率。
先看看Rscript 的帮助文档:
$ Rscript
Usage: /path/to/Rscript [--options] [-e expr [-e expr2 ...] | file] [args]
--options accepted are
--help Print usage and exit
--version Print version and exit
--verbose Print information on progress
--default-packages=list
Where 'list' is a comma-separated set
of package names, or 'NULL'
or options to R, in addition to --no-echo --no-restore, such as
--save Do save workspace at the end of the session
--no-environ Don't read the site and user environment files
--no-site-file Don't read the site-wide Rprofile
--no-init-file Don't read the user R profile
--restore Do restore previously saved objects at startup
--vanilla Combine --no-save, --no-restore, --no-site-file
--no-init-file and --no-environ
'file' may contain spaces but not shell metacharacters
Expressions (one or more '-e <expr>') may be used *instead* of 'file'
See also ?Rscript from within R
(R4.1.2) intern 22:31:10 ~/1.project
参考:Rscripts的使用,以及如何为R脚本传参数 - holy_black_cat - 博客园 (cnblogs.com)[2]
Rscript 可以接受多个args 参数,而在R 脚本中通过commandArgs()这个函数接受这些参数中的变量,接下来就可以通过args<-commandArgs(T)
收集这些变量。
而通过下标访问args,即可以在脚本中获得这些外来变量。
比如脚本如下:
cat > test.R
args <- commandArgs(T)
citefuse_time <- 1
sce <- 1
names <- gsub("./Output/seurat_", "", args[1])
names <- gsub(".Rda", "", names)
print(sce)
save(citefuse_time, sce, file = paste0("./Output/","citefuse_",names,".Rda"))
命令:
Rscript test.R ./Output/seurat_P1.Rda
> [1]
不难注意到,我直接在脚本中library 或save data 了,其实你也可以借助以下参数:
--save
--default-packages=list
当然这就是个人习惯了。
[1]
(13条消息) 如何在linux中后台运行R_zsbo2015的博客-CSDN博客_后台运行r脚本: https://blog.csdn.net/zsbo2015/article/details/111477257
[2]
Rscripts的使用,以及如何为R脚本传参数 - holy_black_cat - 博客园 (cnblogs.com): https://www.cnblogs.com/awishfullyway/p/6632669.html