How to detect/handle user interrupt in Rscript

258 views Asked by At

I have an R script designed for command-line execution via Rscript.exe that includes a long running loop that makes API calls and writes results to a database. The script includes error handling via trycatch for database cleanup:

trycatch({
  # api and database call loop
}, finally = {
  # database cleanup
})

This handles API and database errors well, but a user-interrupt (bash CTRL+C) terminates the execution without triggering the finally block.

Is there any way to allow for a graceful exit initiated by user input? This could be either a way to detect the hard interrupt and handle it or a way to check once per loop if some keyboard input has been made (without pausing the loop to wait for input).

1

There are 1 answers

0
R. Gregorian On

Have you tried adding in an error clause?

trycatch({
    # api and database call loop
    }, 
    error=function(e) {   
            message(paste("ERROR:", e))
            #implement graceful exit
            return(NULL) #or whatever value you want
    },
    finally = {
    # database cleanup
    }
)