Last active
October 24, 2023 19:03
-
-
Save itspluxstahre/fb54e5490d712c9d79f10d7d299dc7ba to your computer and use it in GitHub Desktop.
I needed a stupid braindead way to rerun a command repeatdly if it failed or sometimes even if it succeeded to solve a.... thing.
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
<# | |
.\stupid_runner.ps1 -Command "your-command-here" -MaxRetries 5 -Delay "5s" -RerunOnSuccess | |
DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE | |
Version 2, December 2004 | |
Copyright (C) 2004 Sam Hocevar <[email protected]> | |
Everyone is permitted to copy and distribute verbatim or modified | |
copies of this license document, and changing it is allowed as long | |
as the name is changed. | |
DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE | |
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION | |
0. You just DO WHAT THE FUCK YOU WANT TO. | |
#> | |
param ( | |
[string]$Command = $(throw "You must provide a command to run"), | |
[int]$MaxRetries = 10, | |
[string]$Delay = "10s", | |
[switch]$RerunOnSuccess = $false | |
) | |
function Parse-TimeDelay { | |
param ( | |
[string]$delayStr | |
) | |
$units = @{ | |
's' = 1; | |
'm' = 60; | |
'h' = 3600; | |
'd' = 86400; | |
} | |
$unit = $delayStr[-1].ToString().ToLower() | |
if ($unit -ne $null -and $units.ContainsKey($unit)) { | |
try { | |
return [int]$delayStr.Substring(0, $delayStr.Length - 1) * $units[$unit] | |
} catch { | |
throw "Invalid time format" | |
} | |
} else { | |
try { | |
return [int]$delayStr | |
} catch { | |
throw "Invalid time format" | |
} | |
} | |
} | |
function Run-Command { | |
param ( | |
[string]$command, | |
[int]$maxRetries, | |
[int]$delay, | |
[bool]$rerunOnSuccess | |
) | |
$retries = 0 | |
while ($retries -lt $maxRetries) { | |
try { | |
Invoke-Expression $command | |
Write-Host "Command executed successfully!" | |
if (-not $rerunOnSuccess) { | |
return | |
} | |
} catch { | |
Write-Host "Command failed. Retrying ($retries/$maxRetries) after $delay seconds..." | |
} | |
$retries++ | |
Start-Sleep -Seconds $delay | |
} | |
Write-Host "Maximum retries reached. Exiting." | |
} | |
# Main Execution | |
$delayInSeconds = Parse-TimeDelay -delayStr $Delay | |
Run-Command -command $Command -maxRetries $MaxRetries -delay $delayInSeconds -rerunOnSuccess $RerunOnSuccess |
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
#!/usr/bin/env python3 | |
""" | |
DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE | |
Version 2, December 2004 | |
Copyright (C) 2004 Sam Hocevar <[email protected]> | |
Everyone is permitted to copy and distribute verbatim or modified | |
copies of this license document, and changing it is allowed as long | |
as the name is changed. | |
DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE | |
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION | |
0. You just DO WHAT THE FUCK YOU WANT TO. | |
""" | |
import argparse | |
import subprocess | |
import time | |
def parse_time_delay(delay_str): | |
""" | |
Parse time delay from string to seconds. | |
:param delay_str: Time delay as a string, which can contain units like 's', 'm', 'h', 'd'. | |
:return: Time delay in seconds. | |
""" | |
units = {'s': 1, 'm': 60, 'h': 3600, 'd': 86400} | |
unit = delay_str[-1].lower() | |
if unit in units: | |
try: | |
return int(delay_str[:-1]) * units[unit] | |
except ValueError: | |
raise argparse.ArgumentTypeError("Invalid time format") | |
else: | |
try: | |
return int(delay_str) | |
except ValueError: | |
raise argparse.ArgumentTypeError("Invalid time format") | |
def run_command(command, max_retries, delay, rerun_on_success): | |
""" | |
Execute a command and restart it if it fails or if rerun_on_success is True. | |
:param command: The command to execute. | |
:param max_retries: Maximum number of times to retry if the command fails. | |
:param delay: Time to wait between retries, in seconds. | |
:param rerun_on_success: Whether to rerun the command even if it succeeds. | |
""" | |
retries = 0 | |
while retries < max_retries: | |
process = subprocess.Popen(command, shell=True) | |
exit_code = process.wait() | |
if exit_code == 0: | |
print("Command executed successfully!") | |
if not rerun_on_success: | |
return | |
else: | |
print(f"Command failed. Retrying ({retries}/{max_retries}) after {delay} seconds...") | |
retries += 1 | |
time.sleep(delay) | |
print("Maximum retries reached. Exiting.") | |
def main(): | |
""" | |
Main function to handle command line arguments and call the run_command function. | |
""" | |
parser = argparse.ArgumentParser(description="Run a command and restart it upon failure or success based on the flag.") | |
parser.add_argument("command", type=str, help="The command to execute.") | |
parser.add_argument("--max_retries", type=int, default=10, help="Maximum number of retries. Default is 10.") | |
parser.add_argument("--delay", type=parse_time_delay, default='10s', help="Delay between retries. Supports units like 's', 'm', 'h', 'd'. Default is '10s'.") | |
parser.add_argument("--rerun_on_success", action="store_true", default=False, help="Rerun the command even if it succeeds. Default is False.") | |
args = parser.parse_args() | |
run_command(args.command, args.max_retries, args.delay, args.rerun_on_success) | |
if __name__ == "__main__": | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment