私はをクリックすると、txt
ファイルからサブプロットmatplotlibプロセスを実行し、画像をpng
というファイルに保存しますが、このエラーは処理が成功したとしても発生します。MatplotlibとPyQt4を組み合わせる
私は正直に私は本当にmatplotlibのとPyQtはを組み合わせる方法を理解していない、canvas
、figure
を使用してみてくださいそれでもエラーが発生しました。
これは私のコード
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ファイルを生成する)
0123です誰でもこの問題を解決するのに役立つことを願っております。
ありがとうございます。
ファイル?グラフと 'self.draw()'を含んだ 'layer'を削除しようとしましたが、空のグラフがまだ表示されているのはなぜですか? –
2つのファイルをループしてみようとしていますが、最初のファイル出力は正常ですが、なぜ2つ目のファイル出力が最初の出力と混ざり合って2つのグラフが1つのファイルに混ざっているのですか? –
あなたの要件に合わせて答えを更新してください。 – eyllanesc