I finally fixed the issue by adding a sink(type="output")
when catching the interruption - Ctrl-C
- (this makes the things right for later usage of the standard output - which would remain locked/diversion otherwise):
tryCatch({
# Print one file per piaf
output_dir_piafs <- "OUTPUT_dataset_piafs"
unlink(output_dir_piafs, recursive = TRUE, force = TRUE)
dir.create(output_dir_piafs)
for (i in 1:length(lst_sorted)) {
filename <- paste(output_dir_piafs, "/piaf_", i, ".txt", sep="")
sink(file = filename, append = TRUE)
sink(type = "message")
cat(" ", colnames(file1), "\n")
for (j in 1:length(lst_sorted[[i]])) {
cat(j, " ")
lapply( lst_sorted[[i]][[j]],
function(x) {
cat(as.character(x), " ")
}
)
cat("\n")
}
## back to the console
sink(type="output")
cat(paste(filename, "done !\n"))
}
}, interrupt = function(ex) {
##cat("An interrupt was detected.\n")
sink(type="output") # Restore the standard output !
##print(ex)
}) # tryCatch()
The other way to do (based on the help of user1981275 and Karl Forner), would have been:
tryCatch({
# Print one file per piaf
output_dir_piafs <- "OUTPUT_dataset_piafs_2"
unlink(output_dir_piafs, recursive = TRUE, force = TRUE)
dir.create(output_dir_piafs)
for (i in 1:length(lst_sorted)) {
filename <- paste(output_dir_piafs, "/piaf_", i, ".txt", sep="")
f <- file(filename, 'w')
cat(" ", colnames(file1), "\n", file=f)
for (j in 1:length(lst_sorted[[i]])) {
cat(j, " ", file=f)
lapply( lst_sorted[[i]][[j]],
function(x) {
cat(as.character(x), " ", file=f)
}
)
cat("\n", file=f)
}
flush(f)
close(f)
## back to the console
cat(paste(filename, "done !\n"))
}
}, interrupt = function(ex) {
closeAllConnections()
}) # tryCatch()
This solution has the great advantage to not make a diversion of the standard output, meaning that, even without catching the interruption, the standard output remains active.
Note that Keyboard Interruption handling is still necessary to avoid warnings like:
> warnings()
Warning message:
closing unused connection 3 (OUTPUT_dataset_piafs_2/piaf_16.txt)
Accordingly to ?closeAllConnections
:
‘closeAllConnections’ closes (and destroys) all user connections,
restoring all ‘sink’ diversions as it does so.
Last Note: No real speed difference regarding file writing between those two methods.