gpt4 book ai didi

RCurl:在 Rgui 中显示进度表

转载 作者:行者123 更新时间:2023-12-01 10:49:40 25 4
gpt4 key购买 nike

使用 R.exeRterm.exe,这提供了一个极好的进度表。

page=getURL(url="ftp.wcc.nrcs.usda.gov", noprogress=FALSE) 

在 Rgui 中,我仅限于:

page=getURL(url="ftp.wcc.nrcs.usda.gov", 
noprogress=FALSE, progressfunction=function(down,up) print(down))

它提供了一组非常有限的下载信息。

有什么办法可以改善吗?

最佳答案

I start doubting that with standard R commands it is possible to reprint overwriting the current line, which is what RCurl does in non-GUI mode.

我很高兴地告诉大家我错了。至少对于单行,\r 可以做到这一点。事实上:

conc=function(){
cat(" abcd")
cat(" ABCD", '\n')

}
conc()

# abcd ABCD

但是:

over=function(){
cat(" abcd")
cat("\r ABCD", "\n")
}
over()

# ABCD

鉴于此,我编写了这个 progressDown 函数,它可以监视下载状态重写始终在同一行:

library(RCurl) # Don't forget

### Callback function for curlPerform
progressDown=function(down, up, pcur, width){
total=as.numeric(down[1]) # Total size as passed from curlPerform
cur=as.numeric(down[2]) # Current size as passed from curlPerform
x=cur/total
px= round(100 * x)
## if(!is.nan(x) && px>60) return(pcur) # Just to debug at 60%
if(!is.nan(x) && px!=pcur){
x= round(width * x)
sc=rev(which(total> c(1024^0, 1024^1, 1024^2, 1024^3)))[1]-1
lb=c('B', 'KB', 'MB', 'GB')[sc+1]
cat(paste(c(
"\r |", rep.int(".", x), rep.int(" ", width - x),
sprintf("| %g%s of %g%s %3d%%",round(cur/1024^sc, 2), lb, round(total/1024^sc, 2), lb, px)),
collapse = ""))
flush.console() # if the outptut is buffered, it will go immediately to console
return(px)
}
return(pcur)
}

现在我们可以使用 curlPerform 的回调

curlProgress=function(url, fname){
f = CFILE(fname, mode="wb")
width= getOption("width") - 25 # you can make here your line shorter/longer
pcur=0
ret=curlPerform(url=url, writedata=f@ref, noprogress=FALSE,
progressfunction=function(down,up) pcur<<-progressDown(down, up, pcur, width),
followlocation=T)
close(f)
cat('\n Download', names(ret), '- Ret', ret, '\n') # is success?
}

用一个小样本二进制文件运行它:

curlProgress("http://www.nirsoft.net/utils/websitesniffer-x64.zip", "test.zip")

60%的中间输出是(没有#保护):

  |.................................                      | 133.74KB of 222.75KB  60%

其中 KB,将根据总大小调整为 B, KB, MB, GB

成功状态的最终输出是:

  |.......................................................| 222.61KB of 222.75KB 100%
Download OK - Ret 0

请注意,输出线宽是相对于 R 宽度选项(它控制一行中的最大列数)并且可以通过更改 curlProgress 行进行自定义:

width= getOption("width") - 25

这足以满足我的需求并解决了我自己的问题。

关于RCurl:在 Rgui 中显示进度表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21731548/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com