简体   繁体   English

如何知道应用程序是在本地还是在服务器上运行? (R 闪亮)

[英]How to know if the app is running at local or on server? (R Shiny)

I test my app on my laptop, and then deploy it to shinyapps server.我在我的笔记本电脑上测试我的应用程序,然后将它部署到 Shinyapps 服务器。 Before deploying, I need to remove the statement setting the path, eg,在部署之前,我需要删除设置路径的语句,例如,

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):一个简单的示例代码(如果不删除setwd ,它将在服务器上失败):

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(

    )
))

The standard way to do this in Shiny is with: Sys.getenv('SHINY_PORT') .在 Shiny 中执行此操作的标准方法是: Sys.getenv('SHINY_PORT') You could write something like:你可以这样写:

is_local <- Sys.getenv('SHINY_PORT') == ""

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') == ""编辑 2020:仍然没有官方方法可以做到这一点,但我会选择 Yihui 的方法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 .我不知道这是否正确,但您可以使用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 .当您在本地运行它时,除非您专门更改主机,否则它将是127.0.0.1并且我猜在 Shinyapps 上它会类似于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那种东西应该有用,但我不能保证它是否是最好的解决方案

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"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM