Skip to content

Instantly share code, notes, and snippets.

@DeviNoles
Created April 21, 2024 22:01
Show Gist options
  • Save DeviNoles/638a1038c8119b5fb047aa93d97593b0 to your computer and use it in GitHub Desktop.
Save DeviNoles/638a1038c8119b5fb047aa93d97593b0 to your computer and use it in GitHub Desktop.
import subprocess
import time
def run_command(command, timeout_duration):
try:
# Execute the command with a timeout
process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
stdout, stderr = process.communicate(timeout=timeout_duration)
# Print output and errors
print("Output:", stdout.decode())
if stderr:
print("Error:", stderr.decode())
except subprocess.TimeoutExpired:
print("Command timed out and was terminated")
process.kill()
# Ensure process resources are freed
stdout, stderr = process.communicate()
print("Termination output:", stdout.decode())
if stderr:
print("Termination error:", stderr.decode())
except Exception as e:
print(f"An error occurred: {str(e)}")
def main():
# List of commands to run
commands = [
["python", "main.py", "--symbol", "symbol", "--output", "output_file", "-t", "time"],
["python", "main.py", "--symbol", "symbol", "--output", "output_file", "-t", "time"],
# Add more commands as needed
]
command_timeout = 10 # Timeout in seconds for each command
start_time = time.time()
for command in commands:
current_time = time.time()
elapsed_time = current_time - start_time
# Check if total elapsed time is more than 30 seconds before starting a new command
if elapsed_time > 30:
print("30 seconds have elapsed since the start of the script. Exiting...")
break
# Calculate remaining time for the script and use it as the timeout for the command if less than command_timeout
remaining_time = 30 - elapsed_time
current_command_timeout = min(command_timeout, remaining_time)
print(f"Running command with a timeout of {current_command_timeout} seconds.")
run_command(command, current_command_timeout)
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment