67 lines
2.4 KiB
Python
67 lines
2.4 KiB
Python
# -*- coding: utf-8 -*-
|
|
import time
|
|
import sys
|
|
import signal
|
|
import toml
|
|
from watchdog.observers import Observer
|
|
from watchdog.events import FileSystemEventHandler
|
|
from pathlib import Path
|
|
|
|
|
|
def print_hi(name):
|
|
# Use a breakpoint in the code line below to debug your script.
|
|
print(f'Hi, {name}') # Press Ctrl+F8 to toggle the breakpoint.\
|
|
|
|
|
|
# Обработчик сигнала SIGTERM (сигнал остановки от systemd)
|
|
def handler_stop(signum, frame) -> None:
|
|
print(f'Terminate by signal: {signum}')
|
|
sys.exit(0)
|
|
|
|
|
|
# Чтение файла конфигурации
|
|
def read_toml(file_path):
|
|
try:
|
|
with open(file_path, 'r', encoding='utf-8') as file:
|
|
data = toml.load(file)
|
|
return data
|
|
except FileNotFoundError:
|
|
print(f"Config `{file_path}` not found.")
|
|
sys.exit(1)
|
|
except toml.decoder.TomlDecodeError as e:
|
|
print(f"Error decoding config-file from `{file_path}`: {e}.")
|
|
sys.exit(1)
|
|
|
|
|
|
# Press the green button in the gutter to run the script.
|
|
if __name__ == '__main__':
|
|
# Установка обработчика сигнала
|
|
signal.signal(signal.SIGTERM, handler_stop)
|
|
# Считывание имени config-файла их аргументов командной строки
|
|
try:
|
|
config_file = sys.argv[1] # первый аргумент после имени скрипта
|
|
except IndexError:
|
|
config_file = "tacacs_watcher.conf"
|
|
# Чтение файла конфигурации, приветствие и выставление интервала
|
|
config = read_toml(config_file)
|
|
if 'hello' in config:
|
|
print(config['hello'])
|
|
interval = config['interval'] if 'interval' in config else 1
|
|
# получаем все группы в конфиге
|
|
group_keys = [key for key, value in config.items() if isinstance(value, dict)]
|
|
for group in group_keys:
|
|
print(group)
|
|
|
|
# все обработчики в этом цикле
|
|
try:
|
|
while True:
|
|
# вечный цикл, чтобы программа не завершилась никогда (только принудительно или через SIGTERM)
|
|
print_hi('PyCharm')
|
|
time.sleep(interval)
|
|
except KeyboardInterrupt:
|
|
print('Terminate by `KeyboardInterrupt`.')
|
|
sys.exit(0)
|
|
except ValueError:
|
|
print('Error value in config-file.')
|
|
|