Copy the script after execution

Is it possible to copy the executable lines or the main script to the working directory?

So, my normal scenario: I have a stand-alone script that you only need to find in the working directory, and they will do everything I need. After a few months, I made an update for these scripts, and I would like to have a snapshot from the script when I executed the source code ...

So basically file.copy(ITSELF, '.')or something like that.

+4
source share
2 answers

I think this is what you are looking for:

file.copy(sys.frame(1)$ofile,
          to = file.path(dirname(sys.frame(1)$ofile),
                         paste0(Sys.Date(), ".R")))

This will take the current file and copy it to a new file in the same directory as currentDate.R, for example, 2015-07-14.R

If you want to copy to the working directory instead of the source script directory, use

file.copy(sys.frame(1)$ofile,
          to = file.path(getwd(),
                         paste0(Sys.Date(), ".R")))

, sys.frame(1)$ofile , , . , . , .

:

TBH, , , , ( - ), . , , R , source , ofile . (1) (source()) , ( 0). , /, Global ( ), - .

, :

> sys.frame(1)
Error in sys.frame(1) : not that many frames on the stack

:

> myf <- function() sys.frame(1)
> myf()
<environment: 0x0000000013ad7638>

, , ofile:

> myf <- function() names(sys.frame(1))
> myf()
character(0)
+5

, try ... , - ...

try({
  script_name <- sys.frame(1)$ofile
  copy_script_name <- 
    paste0(sub('\\.R', '', basename(script_name)),
           '_',
           format(Sys.time(), '%Y%m%d%H%M%S'),
           '.R')
  file.copy(script_name,
            copy_script_name)
})

script , . - , script .

0

All Articles