Last active
January 29, 2018 22:28
-
-
Save curtisalexander/5d328078441eb767083793faf268b27c to your computer and use it in GitHub Desktop.
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
# install (if applicable) | |
# install.packages(c("dplyr", | |
# "processx", | |
# "purrr", | |
# "readr")) | |
# libraries | |
suppressWarnings(suppressMessages(library("dplyr"))) | |
suppressWarnings(suppressMessages(library("processx"))) | |
suppressWarnings(suppressMessages(library("purrr"))) | |
suppressWarnings(suppressMessages(library("readr"))) | |
# list of applications to kill | |
kill_list <- c( | |
"calc.exe", | |
"notepad.exe" | |
) | |
# the below calls out to the operating system and runs | |
# the command "tasklist /fo csv" on the Windows command line | |
# its standard output -- what is printed on the screen -- | |
# is captured and stored as a string within the list element named stdout | |
# stdout is then separated as a single character vector and piped into | |
# the read_csv function from readr | |
# the final result is a dataframe with the output from the tasklist command | |
# %>% and %$% are from either dplyr or purrr | |
task_list <- processx::run(commandline = "tasklist /fo csv") %$% | |
stdout %>% | |
readr::read_csv() | |
# filter the dataframe to just those tasks in the list above | |
# note the need for backquotes (``) for the column name as it contains | |
# and embedded space | |
tasks_to_kill <- task_list %>% | |
dplyr::filter(`Image Name` %in% kill_list) | |
# function for printing out the commands that will be run | |
print_task <- function(x) { | |
paste0("taskkill /f / pid ", x) %>% print() | |
} | |
# print out what is about to be performed | |
# extract out the PID column from the dataframe | |
# and pass each value of PID into the print_task function | |
# walk is used for iteratively applying a function that has | |
# side effects to each element in a list | |
tasks_to_kill %$% | |
PID %>% | |
purrr::walk(print_task) | |
# callback = simply echo the line back out | |
# using a callback is better than using the echo option within | |
# processx::run as it will not throw R errors but simply | |
# print out the standard error to the console | |
cb <- function(line, proc) { | |
cat(line, "\n") | |
} | |
# function to actually kill a task | |
kill_task <- function(x) { | |
processx::run(commandline = paste0("taskkill /f /pid ", x), | |
error_on_status = FALSE, | |
stdout_line_callback = cb, | |
stderr_line_callback = cb) | |
} | |
# iterate over all the tasks to kill, killing each one by one | |
tasks_to_kill %$% | |
PID %>% | |
purrr::walk(kill_task) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment