Benjamin Schwetz
Benjamin Schwetz

Reputation: 643

How to detect if function is called inside Rstudio or Jupyter notebook

I am working on a 'high-level' function that requires user input. The way the function asks for input should be different, depending if it is called in an Rstudio session, Jupyter Notebook or terminal.

How can one test for these environments?

I have a really hard time searching for this issue. I have been thinking to use interactive() and getOption("device") to deduct where I am, but I was hoping there might be a more explicit way to achieve this.

Upvotes: 3

Views: 169

Answers (2)

Dirk is no longer here
Dirk is no longer here

Reputation: 368181

RStudio also always sets an environment variable RSTUDIO, among others.

In RStudio:

R> Sys.getenv("RSTUDIO")
[1] "1"
R> 

Standard session:

R> Sys.getenv("RSTUDIO")
[1] ""
R> 

So you can compare to "":

R> Sys.getenv("RSTUDIO") == ""
[1] TRUE
R> 

Upvotes: 1

Benjamin Schwetz
Benjamin Schwetz

Reputation: 643

Partial answer:

To test for Rstudio one can use

.Platform$GUI
# [1] "RStudio" 

which works both on Windows and Linux.

Unfortunately, for terminal and jupyterhub, this is both "X11" (on my linux machine). It could also be a bunch of other things, on other platforms.

However, this works, if we only consider the three expected cases:

.Platform$GUI != "RStudio" & interactive() #TRUE for terminal

.Platform$GUI != "RStudio" & !interactive() #TRUE for Jupyter

Upvotes: 0

Related Questions