2017-06-19 94 views
0

我有一個簡單的GUI程序,當我點擊button它會做從txt文件插曲matplotlib處理和圖像保存爲png文件,但我得到這個錯誤,即使這個過程是成功的。結合Matplotlib與PyQt4的

enter image description here

我嘗試使用canvasfigure但仍然有錯誤,老實說,我真的不知道如何matplotlib和PyQt的結合。

這是我的代碼

import sys 
from os import remove 
from PyQt4.QtCore import * 
from PyQt4.QtGui import * 
import jtextfsm as textfsm 
import matplotlib.pyplot as plt 
import numpy as np 
import io 

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

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

    def flush(self): 
     pass 

class MyClass(object): 
    def __init__(self, device_type=None, ip=None, username=None, password=None, secret=None, command=None, command2=None, command3=None, command4=None): 
     self.device_type = device_type 
     self.ip = ip 
     self.username = username 
     self.password = password 
     self.secret = secret 
     self.command = command 
     self.command2 = command2 
     self.command3 = command3 
     self.command4 = command4 

class sshConnection(QThread): 
    def __init__(self): 
     QThread.__init__(self) 
     self.window = Widget() 

    def __del__(self): 
     self.wait() 

    def run(self): 
     self.runSSH() 

    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") 
    # ------------- SSH Connection 
    def runSSH(self): 
     # do process 
     nameFile = ['Switch-1'] 
     for list in nameFile: 
      self.TextFSM(list) 
      self.Graph(list) 

    # ------------- Convert text file to CSV File 
    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) 
     except IOError: 
      print("Error: There Have File does not appear to exist.") 

    # ------------- Convert Data to Graphic 
    def Graph(self, fileName2): 

     plt.figure(figsize=(8.8, 5.5), dpi=150) 
     plt.rcParams['text.color'] = 'k' 
     plt.rcParams.update({'font.size': 6}) 
     plt.subplots_adjust(hspace=.4, right=.8, bottom=.2) 

     # 1 - show flash 
     plt.subplot(2, 2, 1) 
     try: 
      data = np.loadtxt(fileName2 + '-show-flash.csv', dtype=bytes, delimiter=';', usecols=(0, 1))\ 
       .astype(str, io.StringIO()) 

      slices = data[1] 
      labels = data[0] 
      colors = ['lightskyblue', 'lightcoral'] 
      explode = [0.08, 0.01] 
      pie = plt.pie(slices, labels=labels, colors=colors, explode=explode, startangle=90, shadow=True, 
          autopct='%1.1f%%') 

      plt.title('Flash Memory\n(Bytes)') 
      plt.legend(pie[0], [" ".join(a) for a in zip(labels, slices)], loc='upper right') 
      plt.axis('equal') 
     except IOError: 
      print("Error: There Have File does not appear to exist.") 

     # 2 - show memory statistic 
     plt.subplot(2, 2, 2) 
     try: 
      data = np.loadtxt(fileName2 + '-show-memory-statistic.csv', dtype=bytes, delimiter=';', 
           usecols=(3, 4)).astype(str, io.StringIO()) 
      slices = data[1] 
      labels = data[0] 
      colors = ['lightskyblue', 'lightcoral'] 
      explode = [0.08, 0.01] 
      pie = plt.pie(slices, labels=labels, colors=colors, explode=explode, startangle=90, shadow=True, 
          autopct='%1.1f%%') 

      plt.title('Memory Statistic\n(Bytes)') 
      plt.legend(pie[0], [" ".join(a) for a in zip(labels, slices)], loc='upper right') 
      plt.axis('equal') 
     except IOError: 
      print("Error: There Have File does not appear to exist.") 


     # 3 - show cpu utilization 

     plt.subplot(2, 2, 3) 

     def autolabel(rects): 
      for rect in rects: 
       height = rect.get_height() 
       plt.text(rect.get_x() + rect.get_width()/2, height - 2, '%1.1f%%' % int(height), ha='center', 
         va='bottom') 
     N = 3 
     try: 
      data = np.loadtxt(fileName2 + '-show-process-cpu.csv', 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 

      rects1 = plt.bar(ind, utilization_int, width, color='lightblue',) 

      plt.title("CPU Utilization\n ('%') ") 
      plt.xticks(ind, my_xticks) 
      plt.xlabel("CPU Utilization") 
      plt.ylabel("Percent(%)") 

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

     # 4 - CPU Environtment 
     plt.subplot(2, 2, 4) 

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

     N = 3 
     try: 
      data = np.loadtxt(fileName2 + '-show-env.csv', dtype=bytes, delimiter=';', usecols=2).astype(str) 
      value = data[1] 
      if value == '': 
       try: 
        fan = np.loadtxt(fileName2 + '-show-env.csv', dtype=bytes, delimiter=';', usecols=0).astype(str) 
        system_temp = np.loadtxt(fileName2 + '-show-env.csv', dtype=bytes, delimiter=';', usecols=1).astype(
         str) 
        power = np.loadtxt(fileName2 + '-show-env.csv', dtype=bytes, delimiter=';', usecols=6).astype(str) 
        rps = np.loadtxt(fileName2 + '-show-env.csv', dtype=bytes, delimiter=';', usecols=7).astype(str) 

        uptime = np.loadtxt(fileName2 + '-show-version.csv', dtype=bytes, delimiter=';', usecols=3).astype(
         str) 
        pid = np.loadtxt(fileName2 + '-show-version.csv', dtype=bytes, delimiter=';', usecols=5).astype(str) 
        sn = np.loadtxt(fileName2 + '-show-version.csv', dtype=bytes, delimiter=';', usecols=6).astype(str) 

        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] 

        text = fan_title + ' : ' + fan_status + '\n' + system_temp_title + ' : ' + system_temp_value + '\n' \ 
          + power_tile + ' : ' + power_value + '\n' + rps_tile + ' : ' + rps_value + ' PRESENT' + '\n\n' \ 
          + uptime_title + ' : ' + uptime_value + '\n' + pid_title + ' : ' + pid_value + '\n' + sn_title\ 
          + ' : ' + sn_value 

        plt.title("Cpu Environment\n ('Celcius') ") 
        plt.xlabel('CPU Environment') 
        plt.ylabel('Celcius') 

        plt.text(.15, 1/3, text, style='oblique', bbox={'facecolor': 'white', 'alpha': 0.5, 'pad': 5}) 

        # plt.show('') 
        plt.savefig(fileName2 + '.png', bbox_inches='tight') 
        # Delete CSV File 

       except (IOError): 
        print("Error: There Have File does not appear to exist.") 
        plt.savefig(fileName2 + '.png', bbox_inches='tight') 
        # Delete CSV File 

      else: 

       try: 
        data = np.loadtxt(fileName2 + '-show-env.csv', dtype=bytes, delimiter=';', 
             usecols=(2, 4, 5)).astype(str) 
        fan = np.loadtxt(fileName2 + '-show-env.csv', dtype=bytes, delimiter=';', usecols=0).astype(str) 
        system_temp = np.loadtxt(fileName2 + '-show-env.csv', dtype=bytes, delimiter=';', usecols=1).astype(
         str) 
        system_temp_state = np.loadtxt(fileName2 + '-show-env.csv', dtype=bytes, delimiter=';', 
                usecols=3).astype(str) 

        uptime = np.loadtxt(fileName2 + '-show-version.csv', dtype=bytes, delimiter=';', usecols=3).astype(
         str) 
        pid = np.loadtxt(fileName2 + '-show-version.csv', dtype=bytes, delimiter=';', usecols=5).astype(str) 
        sn = np.loadtxt(fileName2 + '-show-version.csv', dtype=bytes, delimiter=';', usecols=6).astype(str) 

        y_height = np.loadtxt(fileName2 + '-show-env.csv', dtype=bytes, skiprows=1, delimiter=';', 
              usecols=5).astype(int) 

        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 

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

        text2 = pid_title + ' : ' + pid_value + '\n' + sn_title + ' : ' + sn_value +\ 
          '\n\n' + uptime_title + ' : ' + uptime_value 

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

        plt.title("CPU Environment\n ('Celcius') ") 
        plt.xticks(ind, my_xticks) 
        plt.xlabel('CPU Environment') 
        plt.ylabel('Celcius') 
        plt.text(2.4, y_height/2, text) 
        plt.text(-1.59, -y_height/1.77, text2, style='oblique', 
          bbox={'facecolor': 'red', 'alpha': 0.5, 'pad': 5}) 
        autolabel(rects1) 

        # plt.show() 
        plt.savefig(fileName2 + '.png', bbox_inches='tight') 
        # Delete CSV File 
        self.delete_file(fileName2) 

       except (IOError, ValueError): 
        print("Error: There Have File does not appear to exist.") 
        plt.savefig(fileName2 + '.png', bbox_inches='tight') 
        # Delete CSV File 

     except (IOError): 
      print("Error: There Have File does not appear to exist.") 
      plt.savefig(fileName2 + '.png', bbox_inches='tight') 
      #Delete CSV File 



class Widget(QWidget): 
    def __init__(self, parent=None): 
     QWidget.__init__(self, parent=parent) 
     self.setWindowTitle("Network Automation") 
     self.setFixedSize(350, 500) 

     # button generate and add 
     self.btgenerate = QPushButton(self) 
     self.btgenerate.setText('Generate') 
     self.btgenerate.setFixedWidth(70) 

     # Processs textedit 

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

     layout = QGridLayout(self) 
     layout.addWidget(self.btgenerate, 0, 0) 
     layout.addWidget(self.process,1,0) 

     self.btgenerate.clicked.connect(self.runThread) 

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


    def runThread(self): 
     self.process.setText('') 
     self.run_thread = sshConnection() 
     self.run_thread.start() 

app = QApplication(sys.argv) 
app.setStyle('cleanlooks') 
app.processEvents() 
window = Widget() 
sys.stdout = Stream(newText=window.onUpdateText) 
window.show() 
sys.exit(app.exec_()) 

txt文件 https://drive.google.com/file/d/0B_jl0iXmYwS_NGMxZWZEdllyVWc/view?usp=sharing

textfsm文件 https://drive.google.com/drive/folders/0B_jl0iXmYwS_ZWRFTXJjRlcxTWM?usp=sharing (生成所需matplotlib csv文件)

我希望有人幫我解決這個問題,

謝謝。

回答

0

你不應該在與主線程不同的線程中發送一個表示處理已完成的信號,除了使用matplotlib你必須指定後端qt4之外,你可以插入作爲widget的一部分的plot如下圖所示:

要清除您必須使用cla()功能的一個窗口,你的情況:

[ax.cla() for ax in self.axes] 

如果你想顯示你應該使用下面的代碼的情節:

import io 
from os import remove 

import matplotlib 
import numpy as np 
import textfsm 
from PyQt4.QtCore import QObject, pyqtSignal, QThread 
from PyQt4.QtGui import QApplication, QWidget, QPushButton, QTextEdit, QGridLayout, QTextCursor, QSizePolicy 

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 


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

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

    def flush(self): 
     pass 


class sshConnection(QThread): 
    finishedFSM = pyqtSignal(str) 

    def __init__(self): 
     QThread.__init__(self) 

    def __del__(self): 
     self.wait() 

    def run(self): 
     self.runSSH() 

    def runSSH(self): 
     # do process 
     filenames = ['Switch-1'] 
     for filename in filenames: 
      # self.delete_file(filename) 
      self.TextFSM(filename) 
      self.finishedFSM.emit(filename) 

    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) 
     except IOError: 
      print("Error: There Have File does not appear to exist.") 


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.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-env 
     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: 
      print("Error: There Have File does not appear to exist.") 

     # 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: 
      print("Error: There Have File does not appear to exist.") 

     # 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: 
      print("Error: There Have File does not appear to exist.") 

     # show-env 

     N = 3 
     try: 
      data = np.loadtxt('{}-show-env.csv'.format(filename), dtype=bytes, delimiter=';', usecols=2).astype(str) 
      value = data[1] 
      if value == '': 
       try: 
        fan = np.loadtxt('{}-show-env.csv'.format(filename), dtype=bytes, delimiter=';', usecols=0).astype(
         str) 
        system_temp = np.loadtxt('{}-show-env.csv'.format(filename), dtype=bytes, delimiter=';', 
              usecols=1).astype(
         str) 
        power = np.loadtxt('{}-show-env.csv'.format(filename), dtype=bytes, delimiter=';', 
             usecols=6).astype(str) 
        rps = np.loadtxt('{}-show-env.csv'.format(filename), dtype=bytes, delimiter=';', usecols=7).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) 

        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] 

        text = fan_title + ' : ' + fan_status + '\n' + system_temp_title + ' : ' + system_temp_value + '\n' \ 
          + power_tile + ' : ' + power_value + '\n' + rps_tile + ' : ' + rps_value + ' PRESENT' + '\n\n' \ 
          + uptime_title + ' : ' + uptime_value + '\n' + pid_title + ' : ' + pid_value + '\n' + sn_title \ 
          + ' : ' + sn_value 

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

        axes4.text(.15, 1/3, text, style='oblique', bbox={'facecolor': 'white', 'alpha': 0.5, 'pad': 5}) 

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

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

      else: 

       try: 
        data = np.loadtxt('{}-show-env.csv'.format(filename), dtype=bytes, delimiter=';', 
             usecols=(2, 4, 5)).astype(str) 

        fan = np.loadtxt('{}-show-env.csv'.format(filename), dtype=bytes, delimiter=';', usecols=0).astype(
         str) 
        system_temp = np.loadtxt('{}-show-env.csv'.format(filename), dtype=bytes, delimiter=';', 
              usecols=1).astype(
         str) 

        system_temp_state = np.loadtxt('{}-show-env.csv'.format(filename), dtype=bytes, delimiter=';', 
                usecols=3).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=5).astype(int) 

        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 

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

        text2 = pid_title + ' : ' + pid_value + '\n' + sn_title + ' : ' + sn_value + \ 
          '\n\n' + uptime_title + ' : ' + uptime_value 

        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(-1.59, -y_height/1.77, text2, style='oblique', 
           bbox={'facecolor': 'red', 'alpha': 0.5, 'pad': 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): 
        print("Error: There Have File does not appear to exist.") 
        axes4.figure.savefig('{}.png'.format(filename), bbox_inches='tight') 
        # Delete CSV File 

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

     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 Widget(QWidget): 
    def __init__(self, parent=None): 
     QWidget.__init__(self, parent=parent) 
     self.setWindowTitle("Network Automation") 
     self.setFixedSize(350, 500) 

     # button generate and add 
     self.btgenerate = QPushButton(self) 
     self.btgenerate.setText('Generate') 
     self.btgenerate.setFixedWidth(70) 

     # Processs textedit 

     self.process = QTextEdit(self) 
     self.process.setFixedWidth(350) 
     self.process.setLineWrapColumnOrWidth(400) 
     self.process.setLineWrapMode(QTextEdit.FixedPixelWidth) 
     self.process.setReadOnly(True) 

     self.cv = MplCanvas() 

     layout = QGridLayout(self) 
     layout.addWidget(self.btgenerate, 0, 0) 
     layout.addWidget(self.process, 1, 0) 

     self.btgenerate.clicked.connect(self.runThread) 

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

    def runThread(self): 
     self.process.setText('') 
     self.run_thread = sshConnection() 
     self.run_thread.finishedFSM.connect(self.cv.graph) 
     self.run_thread.start() 


if __name__ == '__main__': 
    import sys 

    app = QApplication(sys.argv) 
    app.setStyle('cleanlooks') 
    window = Widget() 
    sys.stdout = Stream(newText=window.onUpdateText) 
    window.show() 
    sys.exit(app.exec_()) 

截圖:

enter image description here

開關1.png

enter image description here

+0

如何,如果我不想顯示GUI圖形,我需要的只是'png'文件?我嘗試刪除包含的'圖層'顯示圖形和'self.draw()'但爲什麼空圖仍然出現? –

+0

我試圖做循環2文件,第一個文件輸出是正常的,但爲什麼第二個文件輸出與第一個輸出混合,所以有2個圖混合到1個文件。 –

+0

已根據您的要求更新答案。 – eyllanesc