figure size(length, width) automatically change when doing looping #8866

Open
NedySuprianto opened this Issue Jul 12, 2017 · 0 comments

Comments

Projects
None yet
1 participant

NedySuprianto commented Jul 12, 2017 edited by dopplershift

i have a simple GUI program to generate a graph from text file, but when i'm doing looping all file's at once i got some graphic output with the size is changed.

Example Output:
https://drive.google.com/drive/folders/0B_jl0iXmYwS_d0hvVE1rWFlPNVE?usp=sharing

Code:

import sys
import qdarkstyle
from os import remove
from PyQt4.QtCore import *
from PyQt4.QtGui import *


import matplotlib

matplotlib.use('QT4Agg')
matplotlib.rcParams['text.color'] = 'k'
matplotlib.rcParams.update({'font.size': 6})

from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.figure import Figure

import jtextfsm as textfsm
import numpy as np
import io
import time
import itertools
import ntpath


class Stream(QObject):
    newText = pyqtSignal(str)

    def write(self, text):
        self.newText.emit(str(text))

    def flush(self):
        pass


class MplCanvas(FigureCanvas):
    """Ultimately, this is a QWidget (as well as a FigureCanvasAgg, etc.)."""

    def __init__(self, parent=None, figsize=(8.8, 5.5), dpi=150):

        fig = Figure(figsize=figsize, dpi=dpi)
        fig.clear()
        fig.subplots_adjust(hspace=.4, right=.8, bottom=.2)

        self.axes = [fig.add_subplot(2, 2, i) for i in range(1, 5)]

        FigureCanvas.__init__(self, fig)
        self.setParent(parent)

        FigureCanvas.setSizePolicy(self, QSizePolicy.Expanding, QSizePolicy.Expanding)
        FigureCanvas.updateGeometry(self)

    def graph(self, filename):

        [ax.cla() for ax in self.axes]
        axes1, axes2, axes3, axes4 = self.axes
        colors = ['lightskyblue', 'lightcoral']
        explode = [0.08, 0.01]

        # show flash
        try:
            data = np.loadtxt('{}-show-flash.csv'.format(filename), dtype=bytes, delimiter=';', usecols=(0, 1)).astype(
                str, io.StringIO())

            slices = data[1]
            labels = data[0]

            pie = axes1.pie(slices, labels=labels, colors=colors, explode=explode, startangle=90, shadow=True,
                            autopct='%1.1f%%')

            axes1.title.set_text('Flash Memory\n(Bytes)')
            axes1.legend(pie[0], [" ".join(a) for a in zip(labels, slices)], loc='upper right')
            axes1.axis('equal')

        except (IOError, ValueError, IndexError):
            print("Error: There Have File does not appear to exist(Memory Statistic).")

        # show-memory-statistic

        try:

            data = np.loadtxt('{}-show-memory-statistic.csv'.format(filename), dtype=bytes, delimiter=';',
                              usecols=(3, 4)).astype(str, io.StringIO())
            slices = data[1]
            labels = data[0]
            pie = axes2.pie(slices, labels=labels, colors=colors, explode=explode, startangle=90, shadow=True,
                            autopct='%1.1f%%')

            axes2.title.set_text('Memory Statistic\n(Bytes)')
            axes2.legend(pie[0], [" ".join(a) for a in zip(labels, slices)], loc='upper right')
            axes2.axis('equal')
        except (IOError, ValueError, IndexError):
            text = 'No Data'
            axes2.axis('off')
            axes2.title.set_text('Memory Statistic')
            axes2.text(.4, .6, text, style='oblique', linespacing=1.5)
            print("Error: There Have File does not appear to exist(Memory Statistic).")

        # show-process-cpu
        N = 3

        try:
            data = np.loadtxt('{}-show-process-cpu.csv'.format(filename), dtype=bytes, delimiter=';',
                              usecols=(0, 1, 2)).astype(str)

            my_xticks = data[0]
            utilization = data[1]
            utilization_int = [int(x) for x in utilization]

            ind = np.arange(N)
            width = 0.5

            rects = axes3.bar(ind, utilization_int, width, color='lightblue', )

            axes3.set_title("CPU Utilization\n ('%') ")

            axes3.set_xticks(ind + width / 2)
            axes3.set_xticklabels(my_xticks)
            axes3.set_xlabel("CPU Utilization")
            axes3.set_ylabel("Percent(%)")

            for rect in rects:
                height = rect.get_height()
                axes3.text(rect.get_x() + rect.get_width() / 2, height - 2, '%1.1f%%' % int(height), ha='center',
                           va='bottom')

        except (IOError, ValueError, IndexError):
            print("Error: There Have File does not appear to exist(Process CPU).")

        # show-env

        N = 3
        try:
            data = np.loadtxt('{}-show-env.csv'.format(filename), dtype=bytes, delimiter=';', usecols=6).astype(str)
            fan_1 = np.loadtxt('{}-show-env.csv'.format(filename), dtype=bytes, delimiter=';', usecols=0).astype(str)
            fan_2 = np.loadtxt('{}-show-env.csv'.format(filename), dtype=bytes, delimiter=';', usecols=1).astype(str)
            fan_ps_1 = np.loadtxt('{}-show-env.csv'.format(filename), dtype=bytes, delimiter=';', usecols=2).astype(str)
            fan_ps_2 = np.loadtxt('{}-show-env.csv'.format(filename), dtype=bytes, delimiter=';', usecols=3).astype(str)
            fan = np.loadtxt('{}-show-env.csv'.format(filename), dtype=bytes, delimiter=';', usecols=4).astype(str)

            hostname = np.loadtxt('{}-show-version.csv'.format(filename), dtype=bytes, delimiter=';', usecols=2).astype(
                str)
            version = np.loadtxt('{}-show-version.csv'.format(filename), dtype=bytes, delimiter=';', usecols=0).astype(
                str)
            os = np.loadtxt('{}-show-version.csv'.format(filename), dtype=bytes, delimiter=';', usecols=4).astype(str)
            uptime = np.loadtxt('{}-show-version.csv'.format(filename), dtype=bytes, delimiter=';', usecols=3).astype(
                str)
            pid = np.loadtxt('{}-show-version.csv'.format(filename), dtype=bytes, delimiter=';', usecols=5).astype(str)
            sn = np.loadtxt('{}-show-version.csv'.format(filename), dtype=bytes, delimiter=';', usecols=6).astype(str)

            value = data[1]
            value_fan_1 = fan_1[1]
            value_fan_2 = fan_2[1]
            value_fanps_1 = fan_ps_1[1]
            value_fanps_2 = fan_ps_2[1]
            value_fan = fan[1]
            if value == '':
                try:
                    fan = np.loadtxt('{}-show-env.csv'.format(filename), dtype=bytes, delimiter=';',
                                          usecols=4).astype(str)
                    system_temp = np.loadtxt('{}-show-env.csv'.format(filename), dtype=bytes, delimiter=';',
                                                  usecols=5).astype(str)
                    power = np.loadtxt('{}-show-env.csv'.format(filename), dtype=bytes, delimiter=';',
                                            usecols=10).astype(str)
                    rps = np.loadtxt('{}-show-env.csv'.format(filename), dtype=bytes, delimiter=';',
                                          usecols=11).astype(str)

                    hostname = np.loadtxt('{}-show-version.csv'.format(filename), dtype=bytes, delimiter=';',
                                               usecols=2).astype(str)
                    version = np.loadtxt('{}-show-version.csv'.format(filename), dtype=bytes, delimiter=';',
                                              usecols=0).astype(str)
                    os = np.loadtxt('{}-show-version.csv'.format(filename), dtype=bytes, delimiter=';',
                                         usecols=4).astype(str)
                    uptime = np.loadtxt('{}-show-version.csv'.format(filename), dtype=bytes, delimiter=';',
                                             usecols=3).astype(str)
                    pid = np.loadtxt('{}-show-version.csv'.format(filename), dtype=bytes, delimiter=';',
                                          usecols=5).astype(str)
                    sn = np.loadtxt('{}-show-version.csv'.format(filename), dtype=bytes, delimiter=';',
                                         usecols=6).astype(str)

                    hostname_title = hostname[0]
                    hostname_status = hostname[1]

                    version_tittle = version[0]
                    version_status = version[1]

                    os_tittle = os[0]
                    os_status = os[1]

                    uptime_title = uptime[0]
                    uptime_value = uptime[1]

                    pid_title = pid[0]
                    pid_value = pid[1]

                    sn_title = sn[0]
                    sn_value = sn[1]

                    fan_title = fan[0]
                    fan_status = fan[1]

                    system_temp_title = system_temp[0]
                    system_temp_value = system_temp[1]

                    power_tile = power[0]
                    power_value = power[1]

                    rps_tile = rps[0]
                    rps_value = rps[1]

                    now = time.strftime("%H:%M, %d %A %B %Y")

                    text = fan_title + ' : ' + fan_status + '\n' + system_temp_title + ' : ' + system_temp_value + '\n' + rps_tile + ' : ' + rps_value + '\n' + power_tile + ' : ' + power_value

                    text2 = hostname_title + ' : ' + hostname_status + '\n' \
                            + pid_title + ' : ' + pid_value + '\n' \
                            + sn_title + ' : ' + sn_value + '\n' \
                            + version_tittle + ' : ' + version_status + '\n' \
                            + os_tittle + ' : \n ' + os_status + '\n\n' \
                            + uptime_title + ' : ' + uptime_value + '\n' \
                            + 'TAKEN TIME : ' + now

                    axes4.set_title("Cpu Environment\n")

                    axes4.axis('off')
                    axes4.text(.3, .5, text, style='oblique', linespacing=1.5)
                    axes4.text(-1.3, 2.8, text2, style='oblique', linespacing=1.5)

                    # plt.show('')
                    axes4.figure.savefig('{}.png'.format(filename), bbox_inches='tight')
                    # Delete CSV File
                    self.delete_file(filename)

                except (IOError, ValueError, IndexError):
                    print("Error: There Have File does not appear to exist(CPU Enviroment-1).")
                    axes4.figure.savefig('{}.png'.format(filename), bbox_inches='tight')
                    # Delete CSV File
                    self.delete_file(filename)

            elif (value_fan_1 != '' and value_fan_2 != '' and value_fanps_1 != '' and value_fanps_2 != '' and value_fan == ''):

                try:
                    data = np.loadtxt('{}-show-env.csv'.format(filename), dtype=bytes, delimiter=';',
                                      usecols=(6, 8, 9)).astype(str)
                    fan_1 = np.loadtxt('{}-show-env.csv'.format(filename), dtype=bytes, delimiter=';',
                                       usecols=0).astype(str)
                    fan_2 = np.loadtxt('{}-show-env.csv'.format(filename), dtype=bytes, delimiter=';',
                                       usecols=1).astype(str)
                    fan_ps_1 = np.loadtxt('{}-show-env.csv'.format(filename), dtype=bytes, delimiter=';',
                                          usecols=2).astype(str)
                    fan_ps_2 = np.loadtxt('{}-show-env.csv'.format(filename), dtype=bytes, delimiter=';',
                                          usecols=3).astype(str)
                    system_temp = np.loadtxt('{}-show-env.csv'.format(filename), dtype=bytes, delimiter=';',
                                             usecols=5).astype(str)
                    system_temp_state = np.loadtxt('{}-show-env.csv'.format(filename), dtype=bytes, delimiter=';',
                                                   usecols=7).astype(str)

                    hostname = np.loadtxt('{}-show-version.csv'.format(filename), dtype=bytes, delimiter=';',
                                          usecols=2).astype(str)
                    version = np.loadtxt('{}-show-version.csv'.format(filename), dtype=bytes, delimiter=';',
                                         usecols=0).astype(str)
                    os = np.loadtxt('{}-show-version.csv'.format(filename), dtype=bytes, delimiter=';',
                                    usecols=4).astype(str)
                    uptime = np.loadtxt('{}-show-version.csv'.format(filename), dtype=bytes, delimiter=';',
                                        usecols=3).astype(str)
                    pid = np.loadtxt('{}-show-version.csv'.format(filename), dtype=bytes, delimiter=';',
                                     usecols=5).astype(str)
                    sn = np.loadtxt('{}-show-version.csv'.format(filename), dtype=bytes, delimiter=';',
                                    usecols=6).astype(str)

                    y_height = np.loadtxt('{}-show-env.csv'.format(filename), dtype=bytes, skiprows=1, delimiter=';',
                                          usecols=9).astype(int)

                    hostname_title = hostname[0]
                    hostname_status = hostname[1]

                    version_tittle = version[0]
                    version_status = version[1]

                    os_tittle = os[0]
                    os_status = os[1]

                    uptime_title = uptime[0]
                    uptime_value = uptime[1]

                    pid_title = pid[0]
                    pid_value = pid[1]

                    sn_title = sn[0]
                    sn_value = sn[1]

                    fan_title = fan_1[0]
                    fan_status = fan_1[1]

                    fan_2_title = fan_2[0]
                    fan_2_status = fan_2[1]

                    fan_ps_1_title = fan_ps_1[0]
                    fan_ps_1_status = fan_ps_1[1]

                    fan_ps_2_title = fan_ps_2[0]
                    fan_ps_2_status = fan_ps_2[1]

                    system_temp_title = system_temp[0]
                    system_temp_value = system_temp[1]

                    system_temp_state_title = system_temp_state[0]
                    system_temp_state_status = system_temp_state[1]

                    my_xticks = data[0]
                    utilization = data[1]
                    utilization_int = [int(x) for x in utilization]

                    ind = np.arange(N)
                    width = 0.5
                    now = time.strftime("%H:%M, %d %A %B %Y")

                    text = fan_title + ': ' + fan_status + '\n' + fan_2_title + ': ' + fan_2_status + '\n' + fan_ps_1_title + ': ' + fan_ps_1_status + '\n' + fan_ps_2_title + ': ' + fan_ps_2_status + '\n' + system_temp_title + ': ' + system_temp_value + '\n' + system_temp_state_title + ': ' + system_temp_state_status

                    text2 = hostname_title + ' : ' + hostname_status + '\n' + pid_title + ' : ' + pid_value + '\n' + sn_title + ' : ' + sn_value + '\n' + version_tittle + ' : ' + version_status + '\n' + os_tittle + ' : \n ' + os_status + '\n\n' + uptime_title + ' : ' + uptime_value + '\n' + 'TAKEN TIME : ' + now

                    rects1 = axes4.bar(ind, utilization_int, width, color='r')

                    axes4.set_title("CPU Environment\n ('Celcius') ")

                    axes4.set_xticks(ind)
                    axes4.set_xticklabels(my_xticks)

                    axes4.set_xlabel('CPU Environment')

                    axes4.set_ylabel('Celcius')
                    axes4.text(2.4, y_height / 2, text)
                    axes4.text(-4, y_height + 120, text2, style='oblique', linespacing=1.5)

                    for rect in rects1:
                        height = rect.get_height()
                        axes4.text(rect.get_x() + rect.get_width() / 2, height - 5, '%d C' % int(height), ha='center',
                                   va='bottom')

                    axes4.figure.savefig('{}.png'.format(filename), bbox_inches='tight')
                    # Delete CSV File
                    self.delete_file(filename)

                except (IOError, ValueError, IndexError):
                    print("Error: There Have File does not appear to exist(CPU Enviroment-2).")
                    axes4.figure.savefig('{}.png'.format(filename), bbox_inches='tight')
                    # Delete CSV File
                    self.delete_file(filename)

            elif (value_fan_1 == '' and value_fan_2 == '' and value_fanps_1 == '' and value_fanps_2 == '' and value_fan == ''):
                try:
                    data = np.loadtxt('{}-show-env.csv'.format(filename), dtype=bytes, delimiter=';',
                                      usecols=(6, 8, 9)).astype(str)
                    system_temp = np.loadtxt('{}-show-env.csv'.format(filename), dtype=bytes, delimiter=';',
                                             usecols=5).astype(str)
                    system_temp_state = np.loadtxt('{}-show-env.csv'.format(filename), dtype=bytes, delimiter=';',
                                                   usecols=7).astype(str)

                    hostname = np.loadtxt('{}-show-version.csv'.format(filename), dtype=bytes, delimiter=';',
                                          usecols=2).astype(str)
                    version = np.loadtxt('{}-show-version.csv'.format(filename), dtype=bytes, delimiter=';',
                                         usecols=0).astype(str)
                    os = np.loadtxt('{}-show-version.csv'.format(filename), dtype=bytes, delimiter=';',
                                    usecols=4).astype(str)
                    uptime = np.loadtxt('{}-show-version.csv'.format(filename), dtype=bytes, delimiter=';',
                                        usecols=3).astype(str)
                    pid = np.loadtxt('{}-show-version.csv'.format(filename), dtype=bytes, delimiter=';',
                                     usecols=5).astype(str)
                    sn = np.loadtxt('{}-show-version.csv'.format(filename), dtype=bytes, delimiter=';',
                                    usecols=6).astype(str)

                    y_height = np.loadtxt('{}-show-env.csv'.format(filename), dtype=bytes, skiprows=1, delimiter=';',
                                          usecols=9).astype(int)

                    hostname_title = hostname[0]
                    hostname_status = hostname[1]

                    version_tittle = version[0]
                    version_status = version[1]

                    os_tittle = os[0]
                    os_status = os[1]

                    uptime_title = uptime[0]
                    uptime_value = uptime[1]

                    pid_title = pid[0]
                    pid_value = pid[1]

                    sn_title = sn[0]
                    sn_value = sn[1]

                    system_temp_title = system_temp[0]
                    system_temp_value = system_temp[1]

                    system_temp_state_title = system_temp_state[0]
                    system_temp_state_status = system_temp_state[1]

                    my_xticks = data[0]
                    utilization = data[1]
                    utilization_int = [int(x) for x in utilization]

                    ind = np.arange(N)
                    width = 0.5
                    now = time.strftime("%H:%M, %d %A %B %Y")

                    text = system_temp_title + ': ' + system_temp_value + '\n' + system_temp_state_title + ': ' + system_temp_state_status

                    text2 = hostname_title + ' : ' + hostname_status + '\n' + pid_title + ' : ' + pid_value + '\n' + sn_title + ' : ' + sn_value + '\n' + version_tittle + ' : ' + version_status + '\n' + os_tittle + ' : \n ' + os_status + '\n\n' + uptime_title + ' : ' + uptime_value + '\n' + 'TAKEN TIME : ' + now

                    rects1 = axes4.bar(ind, utilization_int, width, color='r')

                    axes4.set_title("CPU Environment\n ('Celcius') ")

                    axes4.set_xticks(ind)
                    axes4.set_xticklabels(my_xticks)

                    axes4.set_xlabel('CPU Environment')

                    axes4.set_ylabel('Celcius')
                    axes4.text(2.4, y_height / 2, text)
                    axes4.text(-4, y_height + 180, text2, style='oblique', linespacing=1.5)

                    for rect in rects1:
                        height = rect.get_height()
                        axes4.text(rect.get_x() + rect.get_width() / 2, height - 5, '%d C' % int(height), ha='center',
                                   va='bottom')

                    axes4.figure.savefig('{}.png'.format(filename), bbox_inches='tight')
                    # Delete CSV File
                    self.delete_file(filename)

                except (IOError, ValueError, IndexError):
                    print("Error: There Have File does not appear to exist(CPU Enviroment-3).")
                    axes4.figure.savefig('{}.png'.format(filename), bbox_inches='tight')
                    # Delete CSV File
                    self.delete_file(filename)

            else:

                try:
                    data = np.loadtxt('{}-show-env.csv'.format(filename), dtype=bytes, delimiter=';',
                                      usecols=(6, 8, 9)).astype(str)
                    fan = np.loadtxt('{}-show-env.csv'.format(filename), dtype=bytes, delimiter=';', usecols=4).astype(
                        str)
                    system_temp = np.loadtxt('{}-show-env.csv'.format(filename), dtype=bytes, delimiter=';',
                                             usecols=5).astype(str)
                    system_temp_state = np.loadtxt('{}-show-env.csv'.format(filename), dtype=bytes, delimiter=';',
                                                   usecols=7).astype(str)

                    hostname = np.loadtxt('{}-show-version.csv'.format(filename), dtype=bytes, delimiter=';',
                                          usecols=2).astype(str)
                    version = np.loadtxt('{}-show-version.csv'.format(filename), dtype=bytes, delimiter=';',
                                         usecols=0).astype(str)
                    os = np.loadtxt('{}-show-version.csv'.format(filename), dtype=bytes, delimiter=';',
                                    usecols=4).astype(str)
                    uptime = np.loadtxt('{}-show-version.csv'.format(filename), dtype=bytes, delimiter=';',
                                        usecols=3).astype(str)
                    pid = np.loadtxt('{}-show-version.csv'.format(filename), dtype=bytes, delimiter=';',
                                     usecols=5).astype(str)
                    sn = np.loadtxt('{}-show-version.csv'.format(filename), dtype=bytes, delimiter=';',
                                    usecols=6).astype(str)

                    y_height = np.loadtxt('{}-show-env.csv'.format(filename), dtype=bytes, skiprows=1, delimiter=';',
                                          usecols=9).astype(int)

                    hostname_title = hostname[0]
                    hostname_status = hostname[1]

                    version_tittle = version[0]
                    version_status = version[1]

                    os_tittle = os[0]
                    os_status = os[1]

                    uptime_title = uptime[0]
                    uptime_value = uptime[1]

                    pid_title = pid[0]
                    pid_value = pid[1]

                    sn_title = sn[0]
                    sn_value = sn[1]

                    fan_title = fan[0]
                    fan_status = fan[1]

                    system_temp_title = system_temp[0]
                    system_temp_value = system_temp[1]

                    system_temp_state_title = system_temp_state[0]
                    system_temp_state_status = system_temp_state[1]

                    my_xticks = data[0]
                    utilization = data[1]
                    utilization_int = [int(x) for x in utilization]

                    ind = np.arange(N)
                    width = 0.5
                    now = time.strftime("%H:%M, %d %A %B %Y")

                    text = fan_title + ': ' + fan_status + '\n' + system_temp_title + ': ' + system_temp_value + '\n' + system_temp_state_title + ': ' + system_temp_state_status

                    text2 = hostname_title + ' : ' + hostname_status + '\n' + pid_title + ' : ' + pid_value + '\n' + sn_title + ' : ' + sn_value + '\n' + version_tittle + ' : ' + version_status + '\n' + os_tittle + ' : \n ' + os_status + '\n\n' + uptime_title + ' : ' + uptime_value + '\n' + 'TAKEN TIME : ' + now

                    rects1 = axes4.bar(ind, utilization_int, width, color='r')

                    axes4.set_title("CPU Environment\n ('Celcius') ")

                    axes4.set_xticks(ind)
                    axes4.set_xticklabels(my_xticks)

                    axes4.set_xlabel('CPU Environment')

                    axes4.set_ylabel('Celcius')
                    axes4.text(2.4, y_height / 2, text)
                    axes4.text(-4, y_height + 120, text2, style='oblique', linespacing=1.5)

                    for rect in rects1:
                        height = rect.get_height()
                        axes4.text(rect.get_x() + rect.get_width() / 2, height - 5, '%d C' % int(height), ha='center',
                                   va='bottom')

                    axes4.figure.savefig('{}.png'.format(filename), bbox_inches='tight')
                    # Delete CSV File
                    self.delete_file(filename)

                except (IOError, ValueError, IndexError):
                    print("Error: There Have File does not appear to exist (CPU Enviroment-5).")
                    axes4.figure.savefig('{}.png'.format(filename), bbox_inches='tight')
                    # Delete CSV File
                    self.delete_file(filename)

        except (IOError, ValueError, IndexError):
            now = time.strftime("%H:%M, %d %A %B %Y")

            hostname_title = hostname[0]
            hostname_status = hostname[1]

            version_tittle = version[0]
            version_status = version[1]

            os_tittle = os[0]
            os_status = os[1]

            uptime_title = uptime[0]
            uptime_value = uptime[1]

            pid_title = pid[0]
            pid_value = pid[1]

            sn_title = sn[0]
            sn_value = sn[1]

            x = [1, 2, 3]
            y = [4, 5, 6]

            text = 'No Data'

            text2 = hostname_title + ' : ' + hostname_status + '\n' + pid_title + ' : ' + pid_value + '\n' + sn_title + ' : ' + sn_value + '\n' + version_tittle + ' : ' + version_status + '\n' + os_tittle + ' : \n ' + os_status + '\n\n' + uptime_title + ' : ' + uptime_value + '\n' + 'TAKEN TIME : ' + now
            axes4.axis('off')
            axes4.plot(x,y)
            axes4.lines[0].remove()
            axes4.title.set_text('CPU Environment')
            axes4.text(1.8, 5, text, style='oblique', linespacing=1.5)
            axes4.text(-2, 10, text2, style='oblique', linespacing=1.5)
            print("Error: There Have File does not appear to exist(CPU Enviroment).")
            axes4.figure.savefig('{}.png'.format(filename), bbox_inches='tight')
            # Delete CSV File
            self.delete_file(filename)

        self.draw()

    def delete_file(self, name):
        remove(name + "-show-memory-statistic.csv")
        remove(name + "-show-process-cpu.csv")
        remove(name + "-show-version.csv")
        remove(name + "-show-env.csv")
        remove(name + "-show-flash.csv")


class run_file(QThread):
    finished = pyqtSignal(str)

    def __init__(self, file):
        QThread.__init__(self)
        self.file = file

    def __del__(self):
        self.wait()

    def run(self):
        self.run_textfsm()

    def run_textfsm(self):
        new_paths = list(itertools.chain(*self.file))
        for path in new_paths:
            time.sleep(1)
            name = ntpath.basename(path).split(".")[0]
            self.TextFSM(name)
            self.finished.emit(name)

    def TextFSM(self, nameFile):
        try:
            input_file = open(nameFile + '.txt', encoding='utf-8')  # show version
            raw_text_data = input_file.read()
            input_file.close()

            input_file2 = open(nameFile + '.txt', encoding='utf-8')  # show env
            raw_text_data2 = input_file2.read()
            input_file2.close()

            input_file3 = open(nameFile + '.txt', encoding='utf-8')  # show flash
            raw_text_data3 = input_file3.read()
            input_file3.close()

            input_file4 = open(nameFile + '.txt', encoding='utf-8')  # show memory statistic
            raw_text_data4 = input_file4.read()
            input_file4.close()

            input_file5 = open(nameFile + '.txt', encoding='utf-8')  # show process cpu
            raw_text_data5 = input_file5.read()
            input_file5.close()

            template = open("show-version.textfsm")  # show version
            re_table = textfsm.TextFSM(template)
            fsm_results = re_table.ParseText(raw_text_data)

            template2 = open("show-env.textfsm")  # show env
            re_table2 = textfsm.TextFSM(template2)
            fsm_results2 = re_table2.ParseText(raw_text_data2)

            template3 = open("show-flash.textfsm")  # show flash
            re_table3 = textfsm.TextFSM(template3)
            fsm_results3 = re_table3.ParseText(raw_text_data3)

            template4 = open("show-memory-statistic.textfsm")  # show memory statistic
            re_table4 = textfsm.TextFSM(template4)
            fsm_results4 = re_table4.ParseText(raw_text_data4)

            template5 = open("show-process-cpu.textfsm")  # show process cpu
            re_table5 = textfsm.TextFSM(template5)
            fsm_results5 = re_table5.ParseText(raw_text_data5)

            outfile_name = open(nameFile + "-show-version.csv", "w+")  # show version
            outfile = outfile_name

            outfile_name2 = open(nameFile + "-show-env.csv", "w+")  # show env
            outfile2 = outfile_name2

            outfile_name3 = open(nameFile + "-show-flash.csv", "w+")  # show flash
            outfile3 = outfile_name3

            outfile_name4 = open(nameFile + "-show-memory-statistic.csv", "w+")  # show memory statistic
            outfile4 = outfile_name4

            outfile_name5 = open(nameFile + "-show-process-cpu.csv", "w+")  # show process cpu
            outfile5 = outfile_name5

            print(re_table.header)  # show version
            for s in re_table.header:
                outfile.write("%s;" % s)
            outfile.write("\n")

            counter = 0
            for row in fsm_results:  # show version
                print(row)
                for s in row:
                    outfile.write("%s;" % s)
                outfile.write("\n")
                counter += 1
            print("Write %d records" % counter)

            print(re_table2.header)  # show env
            for s in re_table2.header:
                outfile2.write("%s;" % s)
            outfile2.write("\n")

            counter = 0
            for row in fsm_results2:  # show env
                print(row)
                for s in row:
                    outfile2.write("%s;" % s)
                outfile2.write("\n")
                counter += 1
            print("Write %d records" % counter)

            print(re_table3.header)  # show flash
            for s in re_table3.header:
                outfile3.write("%s;" % s)
            outfile3.write("\n")

            counter = 0
            for row in fsm_results3:  # show flash
                print(row)
                for s in row:
                    outfile3.write("%s;" % s)
                outfile3.write("\n")
                counter += 1
            print("Write %d records" % counter)

            print(re_table4.header)  # show memory statistics
            for s in re_table4.header:
                outfile4.write("%s;" % s)
            outfile4.write("\n")

            counter = 0
            for row in fsm_results4:  # show memory statistics
                print(row)
                for s in row:
                    outfile4.write("%s;" % s)
                outfile4.write("\n")
                counter += 1
            print("Write %d records" % counter)

            print(re_table5.header)  # show process cpu
            for s in re_table5.header:
                outfile5.write("%s;" % s)
            outfile5.write("\n")

            counter = 0
            for row in fsm_results5:  # show process cpu
                print(row)
                for s in row:
                    outfile5.write("%s;" % s)
                outfile5.write("\n")
                counter += 1
            print("Write %d records" % counter)
            print("\n")


        except IOError:
            print("Error: There Have File does not appear to exist.")


class Widget(QWidget):
    def __init__(self, parent=None):
        QWidget.__init__(self, parent=parent)
        self.device_list = []  # object array
        self.file = []  # file array
        self.setWindowTitle("Network Automation")
        # self.setFixedSize(350, 500)

        self.cv = MplCanvas()

        # Button Insert File
        self.btinsert_file = QPushButton(self)
        self.btinsert_file.setText('Insert File')
        self.btinsert_file.setFixedWidth(70)

        self.btgenerate_file = QPushButton(self)
        self.btgenerate_file.setText("Generate File's")
        self.btgenerate_file.setFixedWidth(90)


        # Processs
        processlabel = QLabel("Process", self)

        self.process = QTextEdit(self)
        self.process.setLineWrapColumnOrWidth(500)
        self.process.setLineWrapMode(QTextEdit.FixedPixelWidth)
        self.process.setReadOnly(True)

        # Layout for TextEdit
        sublayout3 = QVBoxLayout()
        sublayout3.addWidget(processlabel)
        sublayout3.addWidget(self.process)

        # Layout for Insert File
        sub2 = QHBoxLayout()
        sub2.addWidget(self.btinsert_file)
        sub2.addWidget(self.btgenerate_file)

        sublayout4 = QVBoxLayout()
        sublayout4.addLayout(sub2)

        layout = QGridLayout(self)
        layout.addLayout(sublayout3, 1, 1)
        layout.addLayout(sublayout4, 0, 1)

        self.btinsert_file.clicked.connect(self.getfile)
        self.btgenerate_file.clicked.connect(self.run_file_thread)

    def onUpdateText(self, text):
        cursor = self.process.textCursor()
        cursor.movePosition(QTextCursor.End)
        cursor.insertText(text)
        self.process.setTextCursor(cursor)
        self.process.ensureCursorVisible()

    # Add file
    def getfile(self):
        filter = "Text (*.txt)"
        names = QFileDialog.getOpenFileNames(self, "Open files", "C:\\", filter)
        self.file.append(names)
        print(self.file)


    def run_file_thread(self):
        if not self.file:
            QMessageBox.question(self, 'Warning', "Insert You're Data First")
        else:
            self.file_thread = run_file(self.file)
            self.connect(self.file_thread, SIGNAL("finished()"), self.btn_file)
            self.file_thread.finished.connect(self.cv.graph)
            self.file_thread.start()

            self.btgenerate_file.setDisabled(True)
            self.btinsert_file.setDisabled(True)

    def btn_file(self):
        self.btgenerate_file.setEnabled(True)
        self.btinsert_file.setEnabled(True)

app = QApplication(sys.argv)
# app.setStyle('Plastique')
app.setStyleSheet(qdarkstyle.load_stylesheet(pyside=False))

app.processEvents()

time.sleep(2)

window = Widget()
sys.stdout = Stream(newText=window.onUpdateText)
window.show()
sys.exit(app.exec_())

Code with all files:

https://drive.google.com/drive/folders/0B_jl0iXmYwS_YTlma1hMRUxSV00?usp=sharing

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment