建议一: TCL/TK
library(tcltk)
win1 <- tktoplevel()
butStop <- tkbutton(win1, text = "Stop",
command = function() {
assign("stoploop", TRUE, envir=.GlobalEnv)
tkdestroy(win1)
})
tkgrid(butStop)
stoploop <- FALSE
while(!stoploop) {
cat(". ")
Sys.sleep(1)
}
cat("\n")
部分代码借鉴自:A button that triggers a function call。
建议 2: 对标准输入进行非阻塞检查。 (请注意:C 不是我的核心能力,我是从网上的一些东西拼凑起来的。)主要思想是在C 中编写一个等待用户输入的函数,并从@987654328 调用它@。
以下片段改编自Non-blocking user input in loop。将以下代码另存为kbhit.c:
#include <stdio.h>
#include <unistd.h>
#include <R.h>
void kbhit(int *result)
{
struct timeval tv;
fd_set fds;
tv.tv_sec = 0;
tv.tv_usec = 0;
FD_ZERO(&fds);
FD_SET(STDIN_FILENO, &fds); //STDIN_FILENO is 0
select(STDIN_FILENO+1, &fds, NULL, NULL, &tv);
*result = FD_ISSET(STDIN_FILENO, &fds);
}
然后,从命令行运行 R CMD SHLIB kbhit.c 将其编译为 R。
最后,在R 中,加载新创建的kbhit.so,编写一个返回C 函数输出的函数(kbhit),然后运行你的循环。 kbhit() 除非收到回车键,否则返回 0。请注意,停止循环的唯一方法是按 enter/return(或硬中断)——如果您想要更灵活的方法,请参阅上面的链接。
dyn.load("kbhit.so")
kbhit <- function() {
ch <- .C("kbhit", result=as.integer(0))
return(ch$result)
}
cat("Hit <enter> to stop\n")
while(kbhit()==0) {
cat(". ")
Sys.sleep(1)
}
More details on the .C interface to R.
在 Windows 机器上:
kbhit.c
#include <stdio.h>
#include <conio.h>
#include <R.h>
void do_kbhit(int *result) {
*result = kbhit();
}
在R:
dyn.load("kbhit.dll")
kbhit <- function() {
ch <- .C("do_kbhit", result=as.integer(0))
return(ch$result)
}
cat("Hit any key to stop\n")
while(kbhit()==0) {
cat(". ")
Sys.sleep(1)
}
附:我通过谷歌搜索把它破解了,所以不幸的是我不知道它是如何工作的或为什么工作(如果它对你有用的话!)。