Use R to kill tasks on Windows
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# for checking and installing packages | |
# extracted from CRAmisc package | |
# https://github.com/curtisalexander/CRAmisc/blob/master/R/install.R | |
check_install <- function(pkgs, repos = NULL, ...) { | |
installed_packages <- installed.packages()[ ,1] | |
for (i in seq_along(pkgs)) { | |
pkg <- pkgs[[i]] | |
if (!pkg %in% installed_packages) { | |
cat(paste0("Need to install: ", pkg, "\n")) | |
if(is.null(repos)) install.packages(pkg, repos = "https://cran.rstudio.com") | |
else install.packages(pkg, repos = repos, ...) | |
} else cat(paste0(pkg, " already installed\n")) | |
} | |
invisible(pkgs) | |
} | |
req_pkgs <- list( | |
"dplyr", | |
"processx", | |
"purrr", | |
"readr" | |
) | |
check_install(req_pkgs) | |
# list of applications to kill | |
kill_list <- c( | |
"calc.exe", | |
"notepad.exe" | |
) | |
# callback | |
cb <- function(line, proc) { | |
cat(line, "\n") | |
} | |
# kill tasks using a single pipeline | |
taskkill <- function(klist) { | |
processx::run(commandline = "tasklist /fo csv") %$% | |
stdout %>% | |
readr::read_csv() %>% | |
dplyr::filter(`Image Name` %in% klist) %$% | |
PID %>% | |
purrr::walk(~ processx::run(commandline = paste0("taskkill /f /pid ", .), | |
error_on_status = FALSE, | |
stdout_line_callback = cb, | |
stderr_line_callback = cb)) | |
} | |
taskkill(kill_list) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment