This repository has been archived by the owner on Mar 11, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
despicable.py
124 lines (102 loc) · 3.85 KB
/
despicable.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
"""
Lightweight multithreading framework for command line tasks
"""
import sys
import os
import argparse
import logging
import signal
import time
import datetime
import Queue
import traceback
from despicable import *
from spinner import Spinner
def pwede_na(cmd_list, message):
"""Minionese for 'can we start?'"""
input_queue = Queue.Queue()
output_queue = Queue.Queue()
result_queue = Queue.Queue()
total = len(cmd_list)
for index, cmd in enumerate(cmd_list):
cmd_tuple = (index, cmd)
logging.info("Queueing CID {}: `{}`".format(index, cmd))
input_queue.put(cmd_tuple)
thread_cap = total if total < THREAD_MAX else THREAD_MAX
logging.info("Selected thread cap: {}".format(thread_cap))
if thread_cap == 1:
word = 'thread'
else:
word = 'threads'
logging.info("Starting concurrent execution")
spinner.start()
spawner = Nefario(input_queue, output_queue, result_queue, thread_cap)
spawner.start()
handler = Gru(result_queue, total, message)
handler.start()
spawner.join()
handler.join()
spinner.stop()
logging.info("Concurrent execution completed")
for thread_id, thread_message in Drain(output_queue):
logging.info("Output from TID {}: {}".format(thread_id, thread_message))
def parse_commands(commands, command_file, message):
command_list = []
if commands:
for command in commands:
command_list.append(command)
if command_file:
with open(command_file) as f:
commands_from_file = f.read().splitlines()
for command in commands_from_file:
if command == "":
continue
if not command[0] == '#':
command_list.append(command)
f.close()
if len(command_list) == 0:
logging.error("No valid commmands detected")
print "Despicable: err: no valid commands detected"
sys.exit(1)
pwede_na(command_list, str(message).strip('[').strip(']').strip("'"))
def signal_handler():
spinner.stop()
print " Aborting despicable..."
time.sleep(0.5)
logging.info("Exiting from keyboard interrupt")
sys.exit(0)
def build_parser():
parser = argparse.ArgumentParser(description=__doc__, formatter_class = argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument('-t', '--thread-max', type=int, default=8, required=False, help="maximum number of threads")
parser.add_argument('-c', '--commands', type=str, nargs="+", required=False, help="a command to be parallelized (must be wrapped in double quotes)")
parser.add_argument('-f', '--command-file', type=str, default="Despicablefile", required=False, help="name of the file that contains commands to be parallelized")
parser.add_argument('-m', '--message', type=str, nargs=1, default="Processing", help="The message to be displayed during concurrent execution")
parser.add_argument('--log-level', type=str, choices=['DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL'], default="INFO", required=False, help="The level at which to log information during execution")
parser.add_argument('--log-file', type=str, default="despicable_logs.txt", required=False, help="The file to log info to during execution")
parser.add_argument('-o', '--omit-logs', action='store_true', default=False, required=False, help="if included, information will not be logged")
return parser
def main():
parser = build_parser()
args = parser.parse_args()
signal.signal(signal.SIGINT, signal_handler)
global spinner
spinner = Spinner()
global THREAD_MAX
THREAD_MAX = args.thread_max
if args.omit_logs:
log_file = "/dev/null"
else:
log_file = args.log_file
numeric_log_level = getattr(logging, args.log_level.upper(), None)
frmt = '%(levelname)s %(asctime)s %(module)s (%(funcName)s): %(message)s'
logging.basicConfig(
filename=log_file,
level=numeric_log_level,
format=frmt,
datefmt="%Y-%m-%d %H:%M:%S"
)
logging.info("Successful logging init")
logging.info("Selected maximum number of threads: {}".format(THREAD_MAX))
parse_commands(args.commands, args.command_file, args.message)
if __name__ == '__main__':
main()