我在脚本中使用readLines(text url),其中readLines(text url)被调用了几百次,其中每个文本url都是唯一的.
大约125次调用readLines(文本URL)后,我收到一个错误,"所有连接都在使用中."
当我使用showConnections(all = TRUE)检查我的打开连接时,对于url连接,我看到:
description class ... isopen
"www.site.com" "url" ... "closed" ...
Run Code Online (Sandbox Code Playgroud)
如何从R环境中删除这些已关闭的连接,以便打开新连接?
另外,我尝试先打开url,将url连接传递给readLines,然后在完成连接后关闭连接,仍然遇到同样的问题.
避免这种问题的最简单方法是在完成连接后显式关闭连接.在R中,最简单的方法是使用on.exit()哪个将确保即使代码中发生错误也会关闭url
read_url <- function(url, ...) {
on.exit(close(url))
readLines(url, ...)
}
showConnections()
g <- read_url("http://www.google.com")
showConnections()
Run Code Online (Sandbox Code Playgroud)