【问题标题】:Wait for user input when running an R script in Linux在 Linux 中运行 R 脚本时等待用户输入
【发布时间】:2023-03-31 16:10:01
【问题描述】:

我有一段代码提示用户输入,并且在 Windows 中运行代码时运行良好。但是,在 Linux 中,它执行每一行而不等待用户输入。

我已将代码添加到单独的函数中,并使用 system("stty -echo") 没有成功。 为什么会发生这种情况以及可以做些什么? (执行命令:Rscript test.R)

require(Biostrings)
read_value <- function(prompt_text = "", prompt_suffix = getOption("prompt"),
                       coerce_to= "character")
{
  prompt <- paste(prompt_text, prompt_suffix)
  system("stty -echo")
  as(readline(prompt), coerce_to)
 }

prints<-function()
{ opt<-as.character(readline(prompt = "Enter parameter values: "))
  system("stty -echo")
  i<-1
  while ((i<=5))
    { if (i==1)
       { expr.filename <- as.character(readline(prompt = "Expression file name: "))
         tryCatch( {expr.file<-read.table(expr.filename)},error=function(e)
             {print("ERROR : Enter valid filename!") return })
       }
      if (i==2)
      {  system("stty -echo")
       fasta.filename <- as.character(readline(prompt = "Fasta file name: "))
       tryCatch( {sequence_data<-read.DNAStringSet(fasta.filename)},error=function(e) 
                {print("ERROR : Enter valid filename!")  return })
      }
     #missing piece of code
    i<-i+1
}

【问题讨论】:

  • 您如何在 Windows 中运行 Rscript test.R?您是从 Windows 命令行运行它吗?我问是因为readline 在从非交互式会话调用时不应提示用户输入,无论平台如何。
  • @Joshua Ulrich - 我正在使用该命令在 Linux 中运行它。
  • @JoshuaUlrich- 但是,我想在 Linux 上进行交互式会话

标签: linux r user-input


【解决方案1】:

您可能需要考虑使用“stdin”中的readLines。提示功能是为记录数据集而设计的。

 cat("Please enter a file name ...")
 fil <- readLines(con="stdin", 1)
 cat(fil, "\n")

另存为 filnam.r .... 使用:

user-linux-prompt$  Rscript filnam.r

【讨论】:

  • -我已经尝试过了,它按原样工作..我试图将它调整到我的代码中,看看它是如何工作的..
猜你喜欢
  • 1970-01-01
  • 2016-10-06
  • 2023-03-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-05-08
相关资源
最近更新 更多