如何使用键盘命令中断 R 中正在运行的代码?

有人能告诉我如何在 R 中中断正在运行的脚本吗?

假设我有一个无限循环或者其他问题,我想停止脚本的运行。有没有一个键盘命令可以做到这一点?

如果有帮助的话,在 Python 中是 Ctrl + c,我在 R 中试过了,但是没有用:)。

我对这个看似简单的问题做了一些搜索,但是没有找到答案。

先谢谢你。

323773 次浏览

Control-C works, although depending on what the process is doing it might not take right away.

If you're on a unix based system, one thing I do is control-z to go back to the command line prompt and then issue a 'kill' to the process ID.

Try out Ctrl + z But it will kill the process, not suspend it.

Self Answer (pretty much summary of other's comments and answers):

  • In RStudio, Esc works, on windows, Mac, and ubuntu (and I would guess on other linux distributions as well).

  • If the process is run in say ubuntu shell (and this is not R specific), for example using:

      Rscript my_file.R
    

    Ctrl + c kills the process

    Ctrl + z suspends the process

  • Within R shell, Ctrl + C kills helps you escape it

I know this is old, but I ran into the same issue. I'm on a Mac/Ubuntu and switch back and forth. What I have found is that just sending a simple interrupt signal to the main R process does exactly what you're looking for. I've ran scripts that went on for as long as 24 hours and the signal interrupt works very well. You should be able to run kill in terminal:

$ kill -2 pid

You can find the pid by running

$ps aux | grep exec/R

Not sure about Windows since I'm not ever on there, but I can't imagine there's not an option to do this as well in Command Prompt/Task Manager

Hope this helps!