S
S
Said Gafarov2021-11-11 09:24:45
Python
Said Gafarov, 2021-11-11 09:24:45

How to find out the number of sections in config.ini set by the user?

Good day Dear coders,
I'm just starting my journey in learning this language, well, like all beginners, I decided to take up my idea right away. Little by little I am moving forward, but when I woke up in the morning I realized that I had made a mistake. I started looking for a solution but didn’t find it ((Sorry for the lyrical digression ....

The essence of the question:
There is a console program in Python3:
618cb6d4b90c1812662544.png
which should ping (not implemented) network nodes (cameras) specified by the user in config.ini and display their availability (UP / DOWN) in the console. If the user entered 100 sections according to a given pattern in the config and all 10 are written in the program, then what to do? How to check and run the program in accordance with the number of sections? Maybe somehow you can not write them separately in Python code?
config .ini

[cam1]
pos=1
name=cam1
area=1-st floor
ip=10.0.1.23
mac=00:1A:C2:7B:00:47

[cam2]
pos=2
name=cam2
area=2-nd floor
ip=10.0.1.24
mac=00:4A:C2:7B:10:42

[cam3]
pos=3
name=cam3
area=3-rd floor
ip=10.0.1.25
mac=00:43:C2:7B:F0:13

Wrote 3 sections for example. In my config there are currently 9 sections.

And the program itself:
import os
import sys
import configparser  # импортируем библиотеку для чтения INI файлов
import colorama # импортируем библиотеку для добавления цвета
from colorama import Fore, Back, Style
colorama.init()

config = configparser.ConfigParser()  # создаём объекта парсера
config.read("config.ini")  # читаем конфиг

print()
print(Fore.YELLOW + 'IP CCTV monitoring system')
print(Style.RESET_ALL)

# 1-ая строчка мониторинга
cam1a = config["cam1"]["pos"]
cam1b = config["cam1"]["name"]
cam1c = config["cam1"]["area"]
cam1d = config["cam1"]["ip"]
cam1e = config["cam1"]["mac"]
cam1f = True
cam1g = "16:25"

# 2-ая строчка мониторинга
cam2a = config["cam2"]["pos"]
cam2b = config["cam2"]["name"]
cam2c = config["cam2"]["area"]
cam2d = config["cam2"]["ip"]
cam2e = config["cam2"]["mac"]
cam2f = True
cam2g = "16:25"

# 3-ья строчка мониторинга
cam3a = config["cam3"]["pos"]
cam3b = config["cam3"]["name"]
cam3c = config["cam3"]["area"]
cam3d = config["cam3"]["ip"]
cam3e = config["cam3"]["mac"]
cam3f = False
cam3g = "16:25"

# 4-ая строчка мониторинга
cam4a = config["cam4"]["pos"]
cam4b = config["cam4"]["name"]
cam4c = config["cam4"]["area"]
cam4d = config["cam4"]["ip"]
cam4e = config["cam4"]["mac"]
cam4f = True
cam4g = "16:25"

# 5-ая строчка мониторинга
cam5a = config["cam5"]["pos"]
cam5b = config["cam5"]["name"]
cam5c = config["cam5"]["area"]
cam5d = config["cam5"]["ip"]
cam5e = config["cam5"]["mac"]
cam5f = True
cam5g = "16:25"

# 6-ая строчка мониторинга
cam6a = config["cam6"]["pos"]
cam6b = config["cam6"]["name"]
cam6c = config["cam6"]["area"]
cam6d = config["cam6"]["ip"]
cam6e = config["cam6"]["mac"]
cam6f = True
cam6g = "16:25"

# 7-ая строчка мониторинга
cam7a = config["cam7"]["pos"]
cam7b = config["cam7"]["name"]
cam7c = config["cam7"]["area"]
cam7d = config["cam7"]["ip"]
cam7e = config["cam7"]["mac"]
cam7f = True
cam7g = "16:25"

# 8-ая строчка мониторинга
cam8a = config["cam8"]["pos"]
cam8b = config["cam8"]["name"]
cam8c = config["cam8"]["area"]
cam8d = config["cam8"]["ip"]
cam8e = config["cam8"]["mac"]
cam8f = True
cam8g = "16:25"

# 9-ая строчка мониторинга
cam9a = config["cam9"]["pos"]
cam9b = config["cam9"]["name"]
cam9c = config["cam9"]["area"]
cam9d = config["cam9"]["ip"]
cam9e = config["cam9"]["mac"]
cam9f = True
cam9g = "16:25"

# Условие проверки статуса первой строчки
if cam1f:
    cam1f = "\033[37m\033[42m{}\033[0m".format(' UP ')
elif cam1f == False:
    cam1f = "\033[37m\033[41m{}\033[0m".format('DOWN')

print(cam1a, cam1b, cam1c, cam1d, cam1e, cam1f, cam1g, sep=" | ")

# Условие проверки статуса второй строчки
if cam2f:
    cam2f = "\033[37m\033[42m{}\033[0m".format(' UP ')
elif cam2f == False:
    cam2f = "\033[37m\033[41m{}\033[0m".format('DOWN')

print(cam2a, cam2b, cam2c, cam2d, cam2e, cam2f, cam2g, sep=" | ")

# Условие проверки статуса третьей строчки
if cam3f == True:
    cam3f = "\033[37m\033[42m{}\033[0m".format(' UP ')
elif cam3f == False:
    cam3f = "\033[37m\033[41m{}\033[0m".format('DOWN')

print(cam3a, cam3b, cam3c, cam3d, cam3e, cam3f, cam3g, sep=" | ")

# Условие проверки статуса четвертой строчки
if cam4f:
    cam4f = "\033[4m\033[37m\033[42m{}\033[0m".format(' UP ')
elif cam4f == False:
    cam4f = "\033[4m\033[37m\033[41m{}\033[0m".format('DOWN')

print(cam4a, cam4b, cam4c, cam4d, cam4e, cam4f, cam4g, sep=" | ")

# Условие проверки статуса пятой строчки
if cam5f:
    cam5f = "\033[4m\033[37m\033[42m{}\033[0m".format(' UP ')
elif cam5f == False:
    cam5f = "\033[4m\033[37m\033[41m{}\033[0m".format('DOWN')

print(cam5a, cam5b, cam5c, cam5d, cam5e, cam5f, cam5g, sep=" | ")

# Условие проверки статуса шестой строчки
if cam6f:
    cam6f = "\033[4m\033[37m\033[42m{}\033[0m".format(' UP ')
elif cam6f == False:
    cam6f = "\033[4m\033[37m\033[41m{}\033[0m".format('DOWN')

print(cam6a, cam6b, cam6c, cam6d, cam6e, cam6f, cam6g, sep=" | ")

# Условие проверки статуса седьмой строчки
if cam7f:
    cam7f = "\033[4m\033[37m\033[42m{}\033[0m".format(' UP ')
elif cam7f == False:
    cam7f = "\033[4m\033[37m\033[41m{}\033[0m".format('DOWN')

print(cam7a, cam7b, cam7c, cam7d, cam7e, cam7f, cam7g, sep=" | ")

# Условие проверки статуса восьмой строчки
if cam8f:
    cam8f = "\033[4m\033[37m\033[42m{}\033[0m".format(' UP ')
elif cam8f == False:
    cam8f = "\033[4m\033[37m\033[41m{}\033[0m".format('DOWN')

print(cam8a, cam8b, cam8c, cam8d, cam8e, cam8f, cam8g, sep=" | ")

# Условие проверки статуса девятой строчки
if cam9f:
    cam9f = "\033[4m\033[37m\033[42m{}\033[0m".format(' UP ')
elif cam9f == False:
    cam9f = "\033[4m\033[37m\033[41m{}\033[0m".format('DOWN')

print(cam9a, cam9b, cam9c, cam9d, cam9e, cam9f, cam9g, sep=" | ")

input() # Работа программы до нажатия какой либо клавиши

Answer the question

In order to leave comments, you need to log in

3 answer(s)
V
Vlad Grigoriev, 2021-11-11
@AzPyCoder

Learn the basics of python about dictionaries and lists, learn loops and use

import configparser
from datetime import time
from pprint import pprint

config = configparser.ConfigParser()  # создаём объекта парсера
config.read("conf.ini")  # читаем конфиг
my_config_parser_dict = {s: dict(config.items(s)) for s in config.sections()}

for block in my_config_parser_dict.values():
    block['bool'] = True
    block['time'] = time(15, 20)
    print(*block.values(), sep='|')

print()
pprint(my_config_parser_dict)

conclusion

1|cam1|1-st floor|10.0.1.23|00:1A:C2:7B:00:47|True|15:20:00
2|cam2|2-nd floor|10.0.1.24|00:4A:C2:7B:10:42|True|15:20:00
3|cam3|3-rd floor|10.0.1.25|00:43:C2:7B:F0:13|True|15:20:00

{'cam1': {'area': '1-st floor',
          'bool': True,
          'ip': '10.0.1.23',
          'mac': '00:1A:C2:7B:00:47',
          'name': 'cam1',
          'pos': '1',
          'time': datetime.time(15, 20)},
 'cam2': {'area': '2-nd floor',
          'bool': True,
          'ip': '10.0.1.24',
          'mac': '00:4A:C2:7B:10:42',
          'name': 'cam2',
          'pos': '2',
          'time': datetime.time(15, 20)},
 'cam3': {'area': '3-rd floor',
          'bool': True,
          'ip': '10.0.1.25',
          'mac': '00:43:C2:7B:F0:13',
          'name': 'cam3',
          'pos': '3',
          'time': datetime.time(15, 20)}}

S
Sergey Gornostaev, 2021-11-11
@sergey-gornostaev

Learn cycles.

A
Alexander, 2021-11-11
@shabelski89

I think it can be something like this.
1) Cycles
2) Classes
3) Execution and interception of OS processes
4) output formatting - here you still need to think about
to do
alignment

from configparser import ConfigParser
from enum import IntEnum
import subprocess
from datetime import datetime
import colorama
from colorama import Fore, Style


class Status(IntEnum):
    UP = 1
    DOWN = 2


class PingStatus(IntEnum):
    success = 0
    failed = 2


class Camera:
    def __init__(self, pos: int, name: str, area: str, ip: str, mac: str):
        self.pos = pos
        self.name = name
        self.area = area
        self.ip = ip
        self.mac = mac
        self.status = None
        self.dt = None

    def __repr__(self):
        return "|".join([str(x).ljust(15) for x in vars(self).values()])

    def check_status(self):
        result = subprocess.call('ping %s -n 2' % self.ip, stderr=subprocess.DEVNULL, stdout=subprocess.DEVNULL)
        if result == PingStatus.success:
            self.status = "\033[4m\033[37m\033[42m{}\033[0m".format(Status.UP.name)
        elif result == PingStatus.failed:
            self.status = "\033[4m\033[37m\033[41m{}\033[0m".format(Status.DOWN.name)
        else:
            self.status = "\033[4m\033[37m\033[41m{}\033[0m".format(Status.DOWN.name)
        self.dt = datetime.now().strftime("%Y.%m.%d %H:%M")


if __name__ == "__main__":
    colorama.init()
    print(Fore.YELLOW + 'IP CCTV monitoring system')
    print(Style.RESET_ALL)
    config = ConfigParser()
    config.read('config.ini')
    cams = {config[x]['name']: Camera(pos=int(config[x]['pos']), name=config[x]['name'], area=config[x]['area'],
                                      mac=config[x]['mac'], ip=config[x]['Ip'])
            for x in config.sections() if x.startswith('cam')}

    for cam in cams.values():
        cam.check_status()
        print(cam)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question