Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

make sure graphics device gets closed

Tags:

plot

r

I am closing the device (here: pdf() ) I am plotting to at the end of my function with dev.off(). However, if the function/loop terminates due to an error the device stays open. When a function gets repeatedly called, this can lead to quite a lot of open devices; and file handles.

How can I make sure the device gets closed even if the function fails?

I do remember that I once saw how to do this, but I cannot remember.

like image 750
Andre Avatar asked Jun 17 '14 16:06

Andre


People also ask

How do I fix error code 43 on video card?

Error Code 43 can be caused by hardware problems or driver or settings corruption. To address this issue, we recommend performing a clean install of latest graphics drivers provided by the system manufacturer since these drivers are customized.

Has stopped this device because it has reported problems code 43?

Sometimes you may see this error message: Windows has stopped this device because it has reported problems (Code 43). This usually means that the driver (which does NOT come from Seagate; this driver comes from Windows) has lost communication with the drive or the driver has crashed.


1 Answers

on.exit() is made for situations just like this. It's good practice to use it whenever opening a (file or other) connection in a non-interactive setting.

f <- function() {
    pdf(tempfile()) # tempfile() so example doesn't clutter up working directory.
    on.exit(dev.off())
    plot(randomNonExistentObjectName)
}

f()
# Error in plot(randomNonExistentObjectName) : 
#   object 'randomNonExistentObjectName' not found

dev.list()
# NULL
like image 72
Josh O'Brien Avatar answered Oct 16 '22 18:10

Josh O'Brien