Форум сайта python.su
Суть в том, что программа должна работать в консоли Windows и выводить информацию через промежутки времени. Интересует, как во время этого процесса ввести команду, например, прерывания цикла?
Еще интересует возможность организации работы одновременно двух потоков. Например, во время работы цикла while иметь возможность выполнять остальной скрипт.
import time start = True while start == True: print 1; time.sleep(1)
Офлайн
# thread_demo.py from threading import Thread, Event from collections import namedtuple, defaultdict import time ThreadInfo = namedtuple('ThreadInfo', 'thread, stop_event') def counter(n=100, interval=5, stop_event=None): while n > 0 and (stop_event is None or not stop_event.is_set()): print(n, 'left') n -= 1 time.sleep(interval) def create_manager(): threads = defaultdict(lambda: None) funcs = defaultdict(lambda: None) funcs['counter'] = counter def thread_manager(thread_id, thread_type=None, command='start', **kwargs): thread_info = threads[thread_id] if thread_info is None and thread_type is not None and command == 'start': func = funcs[thread_type] if func is not None: stop_event = Event() kwargs['stop_event'] = stop_event thread = Thread(target=func, name=thread_id, kwargs=kwargs) threads[thread_id] = ThreadInfo(thread, stop_event) thread.start() elif thread_info is not None and command == 'kill': del(threads[thread_id]) thread_info.stop_event.set() return thread_manager
>>> import thread_demo >>> tm = thread_demo.create_manager() >>> tm('c1', 'counter', n=20, interval=5) >>> tm('c2', 'counter', n=10, interval=10) >>> tm('c3', 'counter', n=42, interval=3) >>> tm('c2', command='kill') >>> tm('c3', command='kill') >>> tm('c1', command='kill')
Отредактировано izekia (Ноя. 7, 2016 22:20:49)
Офлайн