读取R中的用户输入(如密码)而不回显(对于Windows操作系统)

时间:2016-02-04 05:12:16

标签: r windows echo

与基于Linux的系统的工作解决方案相关的问题:Reading user input without echoing

以下代码是从上述问题的答案之一得出的,并不像Windows预期的那样工作。我希望这个函数不会回显用户输入,但它会回显用户输入:

get_password <- function() {
  cat("Password: ")
  #system("stty -echo")
  system("echo off")
  a <- readline()
  #system("stty echo")
  system("echo on")
  cat("\n")
  return(a)
}

我想知道是否有办法在运行Rscript时从R控制台读取用户输入而不在屏幕上显示它。具体来说,我问的是一个适用于Windows操作系统的解决方案。

编辑: 我在Windows Server 2008 x64上运行我的R 3.1.2实例,上面的函数在询问“密码:”时回显用户输入。

1 个答案:

答案 0 :(得分:2)

Markus Gesmann的博客文章提供了我所寻找的解决方案:Simple user interface in R to get login details

R Login pop-up

以下函数getLoginDetails()使用R包tcltkgWidgetstcltk在弹出窗口中获取登录详细信息:

getLoginDetails <- function(){
  ## Based on code by Barry Rowlingson
  ## http://r.789695.n4.nabble.com/tkentry-that-exits-after-RETURN-tt854721.html#none
  require(tcltk)
  tt <- tktoplevel()
  tkwm.title(tt, "Get login details")
  Name <- tclVar("Login ID")
  Password <- tclVar("Password")
  entry.Name <- tkentry(tt,width="20", textvariable=Name)
  entry.Password <- tkentry(tt, width="20", show="*", 
                            textvariable=Password)
  tkgrid(tklabel(tt, text="Please enter your login details."))
  tkgrid(entry.Name)
  tkgrid(entry.Password)

  OnOK <- function()
  { 
    tkdestroy(tt) 
  }
  OK.but <-tkbutton(tt,text=" Login ", command=OnOK)
  tkbind(entry.Password, "<Return>", OnOK)
  tkgrid(OK.but)
  tkfocus(tt)
  tkwait.window(tt)

  invisible(c(loginID=tclvalue(Name), password=tclvalue(Password)))
}
credentials <- getLoginDetails()
## Do what needs to be done
## Delete credentials
rm(credentials)