파이썬/python

[ python ] curses 이용해서 값만 업데이트 되는 터미널 프로그램 만들기

code094 2022. 12. 28. 12:29

환경설정 

Ubuntu 18.04 64bit

 

언어 / 라이브러리 등 

python 

pika 

easynetq 

thread 

curses 

 

개요 

c# 으로 1초 마다 데이터 업데이트 하는 코드 작성 

python 으로 1초마다 데이터 업데이트 되는지 모니터링 하는 터미널 프로그램 만듦 

 

왼쪽 파이썬 터미널 프로그램  /  오른쪽 c# 데이터 보내는 쪽 

 

c# 

간단하게 랜덤값으로 2개씩 데이터 보냄 

public class Monitoring
    {
        public int TestCount { get; set; }
        public int Test1Count { get; set; }
    }
    class CreateTestDataSet
    {
        readonly IBus bus;
        IExchange exchange = null;
        System.Timers.Timer timer = new System.Timers.Timer();
        Random ran = new Random();

        public CreateTestDataSet(IBus b)
        {        
            bus = b;
            exchange = bus.Advanced.ExchangeDeclare("matt", "fanout");

            timer.Interval = 1000;
            timer.Elapsed += T_Elapsed1;
            timer.Start();

        }
        public void TestMonitoring(int test1, int test2)
        {
            var message = new Message<Monitoring>(new Monitoring
            {
                TestCount = test1,
                Test1Count = test2
            });

            bus.Advanced.Publish<Monitoring>(exchange, "routingkey", false, message);
   
        }

        private void T_Elapsed1(object sender, ElapsedEventArgs e)
        {
            int randomint = ran.Next(100);

            int test1 = randomint;
            int test2 = randomint + 10;

            Console.WriteLine($"1 :{test1}  2 : {test2}");
            TestMonitoring(test1, test2);
        }
    }

python 

c# 에서 넘어오는 데이터를 보여준다 

from concurrent.futures import thread
import pika 
import json
import threading
from datetime import datetime
import curses
from curses import wrapper
import time
import sys
import os

monitor_dict = {}



def consume_messages(rabbit_mq_ip):
    try:
        credentials = pika.PlainCredentials('user','password')
        connection = pika.BlockingConnection(
            pika.ConnectionParameters(host=rabbit_mq_ip, virtual_host='/', credentials=credentials))
        channel = connection.channel()
        result = channel.queue_declare(queue='matt', exclusive=True)
        queue_name = result.method.queue
        channel.queue_bind(exchange='monitor_exchange',queue=queue_name, routing_key='routingkey')
        channel.basic_consume(
            queue=queue_name, on_message_callback=rabbit_mq_callback, auto_ack=True) 
        channel.start_consuming()
        print(' [*] Waiting for messages. To exit press CTRL+C')
    except Exception as ex:
        print('consume_messages error : {ex}')    



def rabbit_mq_callback(channel, method, properties, body):
    try:
        json_objs = json.loads(body)
        analyzed_str = ''
        for json_obj in json_objs:
            monitor_dict[json_obj] = json_objs[json_obj]
    except Exception as ex:
        print('rabbit_mq_callback erorr : {ex}')    

def main(stdscr):
    try:
        while True:
            stdscr.clear()
            start_time = time.time()
            update_status(stdscr)
            exec_time = (time.time() - start_time) * 1000
            sleep_time = 1000
            if exec_time > sleep_time:
                sleep_time = 0
            else:
                sleep_time -= int(exec_time)
            curses.napms(sleep_time)
            stdscr.refresh()          
    except KeyboardInterupt:
        print("close program")
    except Exception as e:
        print("Exception: {}".format(e))
    
    

def update_status(stdscr):
    try:
        analyzed_list = []

        for key , value in monitor_dict.items():
            print_output = '{} : {:6} '.format(key, value)
            analyzed_list.append(print_output) 
            stdscr.addstr(print_output)  
            stdscr.addstr("  ") 
            
    except Exception as ex:
        print('update error : {ex}')    




if __name__ == "__main__":
    rabbit_mq_ip = 'localhost'
    if len(sys.argv) < 2:
        print('No RabbitMq server ip was given using localhost')
    else:
        rabbit_mq_ip = sys.argv[1]

    consumer_thread = threading.Thread(target=consume_messages, args=(rabbit_mq_ip,), daemon=True)
    consumer_thread.start()
    wrapper(main)
    consumer_thread.join()