问题
I test my app on my laptop, and then deploy it to shinyapps server. Before deploying, I need to remove the statement setting the path, e.g.,
setwd('/Users/MrY/OneDrive/Data')
Is there a way the code can find out if it's running locally or on server, so that it will be like:
if (isLocal()) {
setwd('/Users/MrY/OneDrive/Data')
}
A trivial sample code (it will fail on server if setwd
isn't removed):
server.R
library(shiny)
setwd('/Users/Yuji/OneDrive/Data/TownState')
data = 'data1.csv' # to test, using an empty .csv file
shinyServer(function(input, output) {
})
ui.R
library(shiny)
shinyUI(pageWithSidebar(
headerPanel("Click the button"),
sidebarPanel(
actionButton("goButton", "Go!")
),
mainPanel(
)
))
回答1:
The standard way to do this in Shiny is with: Sys.getenv('SHINY_PORT')
. You could write something like:
is_local <- Sys.getenv('SHINY_PORT') == ""
回答2:
EDIT 2020: There still is no official way to do this, but I would opt for Yihui's method of is_local <- Sys.getenv('SHINY_PORT') == ""
I don't know if this is the proper way or not, but you could look at the host using session$clientData$url_hostname
. When you run it locally, unless you specifically change the host, it will be 127.0.0.1
and I'm guessing on shinyapps it'll be something like shinyapps.io
. Sample code
runApp(shinyApp(
ui = fluidPage(
),
server = function(input, output, session) {
observe({
if (session$clientData$url_hostname == "127.0.0.1") {
setwd(...)
}
})
}
))
Something of that sort should work, though I can't vouch for whether or not it's the best solution
回答3:
You could retrieve the host name and query that. The computers should have different host names.
library(R.utils)
hname <- System$getHostname()
yields
nodename
"mikes-air-3.wisedom.local"
来源:https://stackoverflow.com/questions/31423144/how-to-know-if-the-app-is-running-at-local-or-on-server-r-shiny