首页 > 解决方案 > 如何使用端口号从 R 中杀死 Windows 应用程序?

问题描述

我是一个愚蠢的问题。如何从 R 传递以下 Windows 命令(杀死在 1234 端口上运行的进程):

for /f "tokens=5" %a in ('netstat -aon ^| find ":1234" ^| find "LISTENING"')
    do taskkill /f /pid %a

到目前为止,我已经尝试...

# Create the string
kill <- "for /f \"tokens=5\" %a in ('netstat -aon ^| find \":1234\" ^| find \"LISTENING\"') do taskkill /f /pid %a"

# Check
cat(shQuote(kill, type="cmd"))
# "for /f \"tokens=5\" %a in ('netstat -aon ^| find \":1234\" ^| find \"LISTENING\"') do taskkill /f /pid %a"

# Run the cmd
system(shQuote(kill, type="cmd"), wait = F)

# Warning message:
#   In system(shQuote(kill, type = "cmd"), wait = F) :
#   '"for /f \"tokens=5\" 0x0p+0 in ('netstat -aon ^| find \":1234\" ^| find \"LISTENING\"') do taskkill /f /pid 0x0p+0"' not found

编辑:我的帮助

我得到了一个引号组合,它给出了(cat)与 win 命令相同的字符串。

kill <- 'for /f "tokens=5" %a in (\'netstat -aon ^| find ":1234" ^| find "LISTENING"\') do taskkill /f /pid %a'
cat(kill)
# From Cat:    for /f "tokens=5" %a in ('netstat -aon ^| find ":1234" ^| find "LISTENING"') do taskkill /f /pid %a
# Win Command: for /f "tokens=5" %a in ('netstat -aon ^| find ":1234" ^| find "LISTENING"') do taskkill /f /pid %a

额外的:

以下代码将在端口 1234 上运行一个闪亮的应用程序。试图从另一个 R 会话中终止该应用程序。

library(shiny)

ui <- fluidPage(

)

server <- function(input, output, session) {

}

shinyApp(ui, server, options = list(launch.browser = TRUE, port = 1234))

标签: rcmd

解决方案


感谢@HenrikB 的建议。是的...以下带有 shell() 函数的代码正在运行...

# Create the string
kill <- 'for /f "tokens=5" %a in (\'netstat -aon ^| find ":1234" ^| find "LISTENING"\') do taskkill /f /pid %a'

# Check
cat(kill)
# From Cat:    for /f "tokens=5" %a in ('netstat -aon ^| find ":1234" ^| find "LISTENING"') do taskkill /f /pid %a
# Win Command: for /f "tokens=5" %a in ('netstat -aon ^| find ":1234" ^| find "LISTENING"') do taskkill /f /pid %a

# Run the cmd
shell(kill)
# E:\Raja\Installed_Software\R-3.5.1>taskkill /f /pid 18772 
# SUCCESS: The process with PID 18772 has been terminated.

推荐阅读