【问题标题】:how to pause an R script until a file has been downloaded?如何暂停 R 脚本,直到下载文件?
【发布时间】:2020-09-30 10:43:56
【问题描述】:

我有以下一段代码,它运行一个下载报告的 python selenium 脚本

library(reticulate)
source_python("C:/Users/Gunathilakel/Desktop/Dashboard Project/Dashboard/PBK-Report-Automation-for-Dashboard-master/pbk automation.py") 

我想确保在脚本执行下一段代码之前,R 会等到前面的代码将文件下载到我的下载文件夹中

my.file.copy <- function(from, to) {
   todir <- dirname(to)
   if (!isTRUE(file.info(todir)$isdir)) dir.create(todir, recursive=TRUE)
   file.copy(from = from,  to = to,overwrite = TRUE)
 }

 my.file.copy(from = "C:/Users/Gunathilakel/Downloads/Issued and Referral Charge.csv",
                to = "C:/Users/Gunathilakel/Desktop/Dashboard Project/Dashboard/RawData/Issued and Referral Charge2020.csv")

我发现了这个问题How to make execution pause, sleep, wait for X seconds in R?

但是是否可以等待执行,直到文件下载完成?

【问题讨论】:

  • 更改您的 Python 脚本以进行同步下载
  • 以@HongOoi 的评论为最佳答案。

标签: r


【解决方案1】:

居然从这个问题中找到了解决办法

Wait for file to exist

library(reticulate)
source_python("C:/Users/Gunathilakel/Desktop/Dashboard Project/Dashboard/PBK-Report-Automation-for-Dashboard-master/pbk automation.py") 

while (!file.exists("C:/Users/Gunathilakel/Downloads/Issued and Referral Charge.csv")) {
  Sys.sleep(1)
}


 # Moves Downloaded CSV file of Issued_and_refused from Downloads --------
 my.file.copy <- function(from, to) {
   todir <- dirname(to)
   if (!isTRUE(file.info(todir)$isdir)) dir.create(todir, recursive=TRUE)
   file.copy(from = from,  to = to,overwrite = TRUE)
 }

 my.file.copy(from = "C:/Users/Gunathilakel/Downloads/Issued and Referral Charge.csv",
                to = "C:/Users/Gunathilakel/Desktop/Dashboard Project/Dashboard/RawData/Issued and Referral Charge2020.csv")

【讨论】:

  • 请注意,如果该文件没有在您期望的位置结束,那么您将陷入无限循环。可能值得添加一个逃生舱口,或者更好地更改 Python 脚本以按照@HongOoi 的建议进行同步下载。
  • @dpritch 我正在使用 selenium 下载文件,使用如下命令driver.find_element(By.XPATH,'//*[@id="ctl00_ContentPlaceHolder1_rvReports_ctl09_ctl04_ctl00_Menu"]/div[7]/a').click() # This clicks on the csv file to be downloaded 可以分享有关如何在 python 脚本中进行同步下载的任何资源。
  • 根据this 看来,在一般情况下,没有办法等到下载完成,您提出的建议可能是最好的办法。但在某些情况下,您可能能够使用 Selenium 提取目标 URL,在这种情况下,您可以使用例如执行下载。 requests 包可以让您更好地控制下载尝试。
  • 还可以使用 for 循环和睡眠来查找文件大小。如果相同则中断循环
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-04-06
  • 2023-04-02
  • 2018-11-06
  • 1970-01-01
  • 2016-12-01
  • 1970-01-01
  • 2015-06-30
相关资源
最近更新 更多