'R: Using source and loop cycle to run a 2nd script
I am using command source in a Script (Script Number 1) to run other script file saved (Script number 2).
My idea is use a loop to read continually the Script number 2 that is modified continually. I Never stop the loop. But Lamentably this dont work.
Always Script number 1 read the original Script number 2 and not change the result when I change the script number 2. I am using a sublime Text to change the script and not stop the loop cycle.
Example:
Example Script number 1:
repeat{
source("C:/Users/myPC/Desktop/script.R")
Sys.sleep(10)
}
Example Script number 2 modified (script saved as script.R in my desktop):
repeat {
print('Checking files')
Sys.sleep(time=10)
}
This run ok. But during the loop cycle I make changes to the script number 2 (and save file) :
Script number 2 modified:
repeat {
print('NOW RE-Checking files')
Sys.sleep(time=10)
}
The result always is this. Not read the script number 2 modified.
[1] "Checking files"
[1] "Checking files"
[1] "Checking files"
[1] "Checking files"
[1] "Checking files"
[1] "Checking files"
Solution 1:[1]
Not knowing what your scripts are really doing, it's a little guess-work, but I'll work on the two things I do know from this:
Checking to see if a file has been changed and then reloading it will work 95-99% or more of the time. Unfortunately, the risk is that whatever is writing the file will still be writing when your script-1 tries to
sourceit: writing contents to a file is never atomic, so you cannot guarantee without some form of file-lock (not supported on all filesystems) or other coordination mechanism.To remedy this, I suggest that what mechanism (sight-unseen) that is modifying script-2 needs to write to a temp-file and then destructively rename it to be
script2.R. While writing to a file is not atomic, renaming/moving a file is atomic. With this, whenscript1.Rnotices that a file has been updated, it will get to read the whole thing unabated.I suggest that instead of running code in
script2.R, you should define a function that is called (repeatedly) by script-1. That way, script-1 retains control and can check for updates inscript2.Rand, as necessary, reload it. The function one writes in script-2 needs to do one thing and then yield control back to the caller; that is, norepeatorwhileloops unless they are very well contained/limited and will not take longer to exit than you expectscript2.Rto be updated. (Recognize that script-2's while/repeat loop will not be interrupted, so plan accordingly.)(
script2.R)work <- function() { print("Checking files") Sys.sleep(10) }(
script1.R)prevmt <- NA repeat { mt <- file.info("script2.R")$mtime if (is.na(prevmt) || prevmt < mt) { source("script2.R") } work() Sys.sleep(10) }
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | r2evans |
