class MyMainWindow(QtWidgets.QWidget): def __init__(self, parent=None): super(MyMainWindow, self).__init__(parent) pg.setConfigOption('background', '#31363b') # 设置背景为灰色 pg.setConfigOption('foreground', 'w') # 设置前景(包括坐标轴,线条,文本等等)为白色。 #pg.setConfigOptions(antialias=True) # 使曲线看起来更光滑,而不是锯齿状 self.ui = Ui_Form() self.ui.setupUi(self) ##创建线程实例 self.thread1 = Thread1() self.thread1.sinOut1.connect(self.slotThread11) def linkSlot(self): self.thread1.link() def startSlot(self): self.thread1.setAndStart("start") def stopSlot(self): self.thread1.setAndStart("stop") def slotThread11(self, text): # 结果输出 # self.ui.textEdit.setPlainText(text) # 格式化时间 timeText = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) self.ui.textEdit.append(timeText + " : " + text) # 自动添加回车
def __init__(self): super().__init__() self.ui = Ui_Form() self.ui.setupUi(self) self.ui.pushButton.clicked.connect(self.pushButton_Click) timer = threading.Timer(1, self.fun_timer) timer.start() self.show()
def __init__(self, parent=None): super(MyMainWindow, self).__init__(parent) pg.setConfigOption('background', '#31363b') # 设置背景为灰色 pg.setConfigOption('foreground', 'w') # 设置前景(包括坐标轴,线条,文本等等)为白色。 #pg.setConfigOptions(antialias=True) # 使曲线看起来更光滑,而不是锯齿状 self.ui = Ui_Form() self.ui.setupUi(self) ##创建线程实例 self.thread1 = Thread1() self.thread1.sinOut1.connect(self.slotThread11)
class AppWindow(QDialog): def __init__(self): super().__init__() self.ui = Ui_Form() self.ui.setupUi(self) self.ui.pushButton.clicked.connect(self.pushButton_Click) timer = threading.Timer(1, self.fun_timer) timer.start() self.show() def fun_timer(self): ticks = time.strftime("%Y-%m-%d %H:%m:%S", time.localtime()) self.ui.lcdNumber.display(ticks) global timer timer = threading.Timer(1, self.fun_timer) timer.start() def pushButton_Click(self): NumberCount = self.ui.lcdNumber.value() QMessageBox.about(self, 'PyQt', str(NumberCount)) NumberCount += 1 self.ui.lcdNumber.display(NumberCount) ticks = time.strftime("%Y-%m-%d %H:%m:%S", time.localtime()) global changebtn_bool if changebtn_bool: labelstring = ticks changebtn_bool = False else: labelstring = ticks changebtn_bool = True self.ui.label_show.setText(labelstring) self.ui.progressBar.setValue(int(time.strftime("%S", time.localtime()))) global count if count > 3: buttonReply = QMessageBox.question( self, 'PyQt5 message', "Do you want Exit?", QMessageBox.Yes | QMessageBox.No, QMessageBox.No) if buttonReply == QMessageBox.Yes: global app app.exit() else: print('No clicked.') else: count += 1
def __init__(self, parent=None): super().__init__() self.widget = QWidget() self.ui = Ui_Form() self.db_engine = None self.ifname_list = ['eth'+str(i) for i in range(1, 11)] # utm interface name list self.ui.setupUi(self.widget) self.prevViewPage = None # view list의 item index, 화면전환 시 사용. self.cpuCanvas, self.memCanvas, self.diskCanvas = [tim.SimpleMplCanvas() for _ in range(3)] self.cpuThread, self.memThread, self.diskThread = tim.PlotterThread(), tim.PlotterThread(), tim.PlotterThread() pmb.setupManagedObject() self.serverList = pmb.getVmList() self.networkList = ['HeadUTM'] serverModel = QStringListModel() serverModel.setStringList(self.serverList) serverItemCount = serverModel.rowCount() # model item count self.ui.serverListView.setModel(serverModel) networkModel = QStringListModel() networkModel.setStringList(self.networkList) self.ui.networkListView.setModel(networkModel) self.ui.verticalLayout.setAlignment(Qt.AlignTop) self.ui.serverListView.setVisible(False) self.ui.networkListView.setVisible(False) # listview category info added, select page self.ui.serverListView.clicked.connect(lambda index: self.selectServerPage(index, 'server')) self.ui.networkListView.clicked.connect(lambda index: self.selectNetworkPage(index, 'network')) self.ui.HeadUTM_tab.currentChanged.connect(self.changeTab) self.ui.dashboardButton.clicked.connect(self.itemToggle) self.ui.serverButton.clicked.connect(self.itemToggle) self.ui.networkButton.clicked.connect(self.itemToggle) self.ui.stackedWidget.setCurrentIndex(0) # first page in start self.widget.show()
class MyMainWindow(QtWidgets.QWidget): def __init__(self, parent=None): super(MyMainWindow, self).__init__(parent) pg.setConfigOption('background', '#31363b') # 设置背景为灰色 pg.setConfigOption('foreground', 'w') # 设置前景(包括坐标轴,线条,文本等等)为白色。 #pg.setConfigOptions(antialias=True) # 使曲线看起来更光滑,而不是锯齿状 self.ui = Ui_Form() self.ui.setupUi(self) ##创建线程实例 self.thread1 = Thread1() self.thread1.sinOut1.connect(self.slotThread11) self.thread1.sinOut2.connect(self.slotThread12) def linkSlot(self): self.thread1.link() def startSlot(self): self.data = [] # 初始化list self.thread1.setAndStart("continuous") def stopSlot(self): self.thread1.setAndStart("stop") def slotThread11(self, text): # 结果输出 # self.ui.textEdit.setPlainText(text) # 格式化时间 timeText = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) self.ui.textEdit.append(timeText + " : " + text) # 自动添加回车 def slotThread12(self, value): # 结果输出 text = '{:.3f}'.format(value) self.ui.lcdNumber.display(text) #连续进行绘图 self.ui.graphicsView.clear() # 初始化图,不然似乎会发生不好的事情 self.data.append(value) self.ui.graphicsView.plot(self.data, pen=pg.mkPen(color='#3daee9', width=4))
def __init__(self,parent=None): QtGui.QWidget.__init__(self,parent) self.ui = Ui_Form() self.ui.setupUi(self) default_dir = os.getcwd() self.ui.lineEdit_choose_directory.setText(default_dir) self.ui.toolButton_choose_directory.clicked.connect(self.toolButton_choose_directory) self.ui.radioButton_search.setChecked(True) self.ui.pushButton_execute.clicked.connect(self.pushButton_execute) self.ui.listWidget_show_dst_files.setSortingEnabled(True) self.ui.label_notification.setStyleSheet("QLabel{color: black;}") self.ui.lineEdit_choose_directory.editingFinished.connect(self.handle_lineEdit_choose_directory) self.ui.lineEdit_extension.textEdited.connect(self.handle_lineEdit_extension) self.ui.lineEdit_suffix.textEdited.connect(self.handle_lineEdit_suffix) self.ui.lineEdit_search_word.textEdited.connect(self.handle_lineEdit_search_word) self.ui.lineEdit_replace_word.textEdited.connect(self.handle_lineEdit_replace_word)
class MyWindow(QObject): # QWidget-> QObejct로 변경. UI thread와 logic thread 분리? 2018.04.04 """docstring for MyMainWindow""" send_fig = pyqtSignal(Axes, vim.VirtualMachine, int, str, name='send_fig' ) stop_plotter = pyqtSignal(name='start_plotter') def __init__(self, parent=None): super().__init__() self.widget = QWidget() self.ui = Ui_Form() self.db_engine = None self.ifname_list = ['eth'+str(i) for i in range(1, 11)] # utm interface name list self.ui.setupUi(self.widget) self.prevViewPage = None # view list의 item index, 화면전환 시 사용. self.cpuCanvas, self.memCanvas, self.diskCanvas = [tim.SimpleMplCanvas() for _ in range(3)] self.cpuThread, self.memThread, self.diskThread = tim.PlotterThread(), tim.PlotterThread(), tim.PlotterThread() pmb.setupManagedObject() self.serverList = pmb.getVmList() self.networkList = ['HeadUTM'] serverModel = QStringListModel() serverModel.setStringList(self.serverList) serverItemCount = serverModel.rowCount() # model item count self.ui.serverListView.setModel(serverModel) networkModel = QStringListModel() networkModel.setStringList(self.networkList) self.ui.networkListView.setModel(networkModel) self.ui.verticalLayout.setAlignment(Qt.AlignTop) self.ui.serverListView.setVisible(False) self.ui.networkListView.setVisible(False) # listview category info added, select page self.ui.serverListView.clicked.connect(lambda index: self.selectServerPage(index, 'server')) self.ui.networkListView.clicked.connect(lambda index: self.selectNetworkPage(index, 'network')) self.ui.HeadUTM_tab.currentChanged.connect(self.changeTab) self.ui.dashboardButton.clicked.connect(self.itemToggle) self.ui.serverButton.clicked.connect(self.itemToggle) self.ui.networkButton.clicked.connect(self.itemToggle) self.ui.stackedWidget.setCurrentIndex(0) # first page in start self.widget.show() # when click toolbox button in left side, collapse/expand view def itemToggle(self): btn = self.sender() if btn.objectName() == 'dashboardButton': self.ui.serverListView.setVisible(False) self.ui.networkListView.setVisible(False) self.ui.stackedWidget.setCurrentIndex(0) # stacked index 0: dashboard page elif btn.objectName() == 'serverButton': # page name: serverSummary self.ui.serverListView.setVisible(True) self.ui.networkListView.setVisible(False) stackedWidget = self.ui.stackedWidget.findChild(QObject, 'serverSummary', Qt.FindDirectChildrenOnly) self.ui.stackedWidget.setCurrentWidget(stackedWidget) elif btn.objectName() == 'networkButton': # page name: networkSummary self.ui.serverListView.setVisible(False) self.ui.networkListView.setVisible(True) stackedWidget = self.ui.stackedWidget.findChild(QObject, 'networkSummary', Qt.FindDirectChildrenOnly) self.ui.stackedWidget.setCurrentWidget(stackedWidget) else: self.ui.serverListView.setVisible(False) self.ui.networkListView.setVisible(False) self.ui.stackedWidget.setCurrentIndex(0) # tab widget에서 tab click 시 slot, other event: selectNetworkPage def changeTab(self, i): signal_source = self.sender() # ex: HeadUTM_tab tabName = signal_source.tabText(i) tabPage = signal_source.widget(i) # ex: current tab widget: HeadUTM_day deviceName, c_interval = tabPage.objectName().split('_') scrollArea = tabPage.findChild(QScrollArea,'scrollArea_'+ c_interval) # find scrollArea for each interval sampling_mean_interval= None if tabName == '일간': sampling_mean_interval = '10T' elif tabName == '주간': sampling_mean_interval = '30T' elif tabName == '월간': sampling_mean_interval = '30T' if_usage_info_list = utm.get_ifusage_dafaframes(self.db_engine, self.ifname_list, c_interval=c_interval, sampling_mean_interval=sampling_mean_interval) plotter = muw.CanvasWidget(if_usage_info_list) scrollArea.setWidget(plotter) # index: index of listview def selectServerPage(self, index, category): ''' Main StackedWidget에서 Server Name이용하여 해당 child widget을 찾는다. Top Layout을 찾아 20초 간격으로 실시간 갱신 되는 graph를 위해 cpu, memory, disk 개의 canvas를 추가하고 thread를 연결한다. ''' serverName = index.data() # host name in domain # listview의 각 항목을 click 할 때마다, canvas clear, plotter stop. thread 실행 중지 if self.prevViewPage != serverName: # emit Plotter stop signal self.stop_plotter.emit() if self.cpuThread.isRunning(): self.cpuCanvas.axes.clear() self.cpuThread.terminate() self.cpuThread.wait() if self.memThread.isRunning(): self.memCanvas.axes.clear() self.memThread.terminate() self.memThread.wait() if self.diskThread.isRunning(): self.diskCanvas.axes.clear() self.diskThread.terminate() self.diskThread.wait() # staked widget의 child widget, 즉 Page를 찾는다. stackedWidget = self.ui.stackedWidget.findChild(QObject, serverName, Qt.FindDirectChildrenOnly) if stackedWidget: self.ui.stackedWidget.setCurrentWidget(stackedWidget) # Page내 graph를 포함하고 있는 layout를 찾는다. topLayout = stackedWidget.findChild(QHBoxLayout, serverName+'TopLayout') if topLayout != None: if topLayout.count() == 0: # 각 canvas를 topLayout에 추가 topLayout.addWidget(self.cpuCanvas) topLayout.addWidget(self.memCanvas) topLayout.addWidget(self.diskCanvas) self.cpuCanvas.axes.set_title('CPU Usage (%)') #self.cpuCanvas.fig.set_facecolor('lightblue') #self.cpuCanvas.fig.set_edgecolor('green') self.cpuCanvas.fig.subplots_adjust(left=0.1, right=0.95) self.memCanvas.axes.set_title('Atcive Memory (GB)') #self.memCanvas.fig.set_facecolor('lightgreen') self.memCanvas.fig.subplots_adjust(left=0.1, right=0.95) self.diskCanvas.axes.set_title('Disk Usage (MBps)') #self.diskCanvas.fig.set_facecolor('#EDC4F9') self.diskCanvas.fig.subplots_adjust(left=0.125, right=0.99) moid = pmb.getManagedObjectRefId(serverName) numCPU = mvars.cpus[serverName] # 해당 Canvas를 연결해서 각 Plotter를 생성: cid: 2, 32, 125 self.cpuPlotter = tim.SimplePlotter(self.cpuCanvas.axes, moid, 2, numCPU=numCPU, category='cpu') self.memPlotter = tim.SimplePlotter(self.memCanvas.axes, moid, 32, category='mem') self.diskPlotter = tim.SimplePlotter(self.diskCanvas.axes, moid, 125, category='disk') # 각 Plotter를 해당 Thread로 이동 self.cpuPlotter.moveToThread(self.cpuThread) self.memPlotter.moveToThread(self.memThread) self.diskPlotter.moveToThread(self.diskThread) # 해당 thread에 signal 연결 self.cpuThread.started.connect(self.cpuPlotter.start) # tiemr 시작, 20초 후 replot 수행 self.cpuThread.started.connect(self.cpuPlotter.startplot) # thread시작과 동시에 지난 30분간 성능 데이터 수집 및 plotting self.memThread.started.connect(self.memPlotter.start) self.memThread.started.connect(self.memPlotter.startplot) self.diskThread.started.connect(self.diskPlotter.start) self.diskThread.started.connect(self.diskPlotter.startplot) # 별도 signal을 생성해서 listview index(item) 변경 시, plotting 중지 후 plotter object delete. 2018. 04.04 self.stop_plotter.connect(self.cpuPlotter.stop) self.stop_plotter.connect(self.cpuPlotter.deleteLater) self.stop_plotter.connect(self.memPlotter.stop) self.stop_plotter.connect(self.memPlotter.deleteLater) self.stop_plotter.connect(self.diskPlotter.stop) self.stop_plotter.connect(self.diskPlotter.deleteLater) # plotter update signal을 해당 canvas update plot에 연결 self.cpuPlotter.return_fig.connect(self.cpuCanvas.update_plot) self.memPlotter.return_fig.connect(self.memCanvas.update_plot) self.diskPlotter.return_fig.connect(self.diskCanvas.update_plot) # 각 thread start self.cpuThread.start() self.memThread.start() self.diskThread.start() # 화면 하단에 해당 서버의 구성정보를 표시하기 위한 텍스트 브라우저 검색: 디자이너에서 고정폭 폰트(monospaced font) 설정 (Courier, 가독성) # 확인 필요할때:fixedFont = QFontDatabase.systemFont(QFontDatabase.FixedFont) # from PyQt5.QtGui import QFont # font = QFont('Monospace') # font.setStyleHint(QFont.TypeWriter) # font.setPointSize(12) confStatus = stackedWidget.findChild(QTextBrowser, serverName+'Info') content = pmb.si.content vchtime = pmb.si.CurrentTime() vminfo = GetVmInfoMetrics(moid, content, vchtime, 1) vminfo_list = GetDisplayVmInfo_rjust(vminfo) for info in vminfo_list: confStatus.append(info) vminfo, vminfo_list = None, None gc.collect() else: self.ui.stackedWidget.setCurrentIndex(0) self.prevViewPage = serverName def selectNetworkPage(self, index, category): ''' Network device name을 이용하여 stackedWidget 내에 해당 widget을 찾는다. ''' deviceName = index.data() # network device name if self.db_engine == None: self.db_engine = utm.create_db_engine() # staked widget의 child widget, 즉 Page를 찾는다. stackedWidget = self.ui.stackedWidget.findChild(QObject, deviceName, Qt.FindDirectChildrenOnly) if stackedWidget: self.ui.stackedWidget.setCurrentWidget(stackedWidget) # find Tab Widget under stackedWidget tabWidgetName = deviceName + '_tab' tabWidget = stackedWidget.findChild(QTabWidget, tabWidgetName) tabWidget.setCurrentIndex(0) # for daily tabPage = tabWidget.widget(0) # ex: current tab widget: HeadUTM_day c_interval = tabPage.objectName().split('_')[1] scrollArea = tabPage.findChild(QScrollArea,'scrollArea_'+ c_interval) if_usage_info_list = utm.get_ifusage_dafaframes(self.db_engine, self.ifname_list, c_interval=c_interval, sampling_mean_interval='10T') plotter = muw.CanvasWidget(if_usage_info_list) scrollArea.setWidget(plotter)
class MyMainWindow(QtWidgets.QWidget): def __init__(self, parent=None): super(MyMainWindow, self).__init__(parent) pg.setConfigOption('background', '#31363b') # 设置背景为灰色 pg.setConfigOption('foreground', 'w') # 设置前景(包括坐标轴,线条,文本等等)为白色。 #pg.setConfigOptions(antialias=True) # 使曲线看起来更光滑,而不是锯齿状 self.ui = Ui_Form() self.ui.setupUi(self) ##创建线程实例 self.thread1 = Thread1() self.thread1.sinOut1.connect(self.slotThread11) self.thread1.sinOut2.connect(self.slotThread12) def linkSlot(self): self.thread1.link() def startSlot(self): self.thread1.setAndStart(flag1="start") def stopSlot(self): self.thread1.setAndStart(flag1="stop") def buttonClicked(self): # click one of the nine buttons sender = self.sender().objectName() # 运动模式 if sender == "pushButton_1": # ReleaseAll self.thread1.setAndStart(flag="freeAll") elif sender == "pushButton_2": # LockAll self.thread1.setAndStart(flag="lockAll") elif sender == "pushButton_3": # test at self.thread1.setAndStart(flag="at") elif sender == "pushButton_4": # release J1 self.thread1.setAndStart(flag="release", value=b"1") elif sender == "pushButton_5": # release J2 self.thread1.setAndStart(flag="release", value=b"2") elif sender == "pushButton_6": # release J3 self.thread1.setAndStart(flag="release", value=b"3") elif sender == "pushButton_7": # release J4 self.thread1.setAndStart(flag="release", value=b"4") elif sender == "pushButton_8": # release J5 self.thread1.setAndStart(flag="release", value=b"5") elif sender == "pushButton_9": # release J6 self.thread1.setAndStart(flag="release", value=b"6") def slotThread11(self, text): # 结果输出 # self.ui.textEdit.setPlainText(text) # 格式化时间 timeText = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) self.ui.textEdit.append(timeText + " : " + text) # 自动添加回车 def slotThread12(self, text): # show value # deal with read value channel = text[-3:-2] # get channel number value = float(int(text[:6], 16)) # get HEX value and change it to int # change to a voltage value valueText = '{:.3f}'.format(value * 2.5 / 16777215) if channel == "0": self.ui.lcdNumber_1.display(valueText) elif channel == "1": self.ui.lcdNumber_2.display(valueText) elif channel == "2": self.ui.lcdNumber_3.display(valueText) elif channel == "3": self.ui.lcdNumber_4.display(valueText) elif channel == "4": self.ui.lcdNumber_5.display(valueText) elif channel == "5": self.ui.lcdNumber_6.display(valueText) elif channel == "6": self.ui.lcdNumber_7.display(valueText) elif channel == "7": self.ui.lcdNumber_8.display(valueText) elif channel == "8": self.ui.lcdNumber_9.display(valueText) elif channel == "9": self.ui.lcdNumber_10.display(valueText) elif channel == "A": self.ui.lcdNumber_11.display(valueText) elif channel == "B": self.ui.lcdNumber_12.display(valueText)
class mainUI(QtGui.QWidget): def __init__(self,parent=None): QtGui.QWidget.__init__(self,parent) self.ui = Ui_Form() self.ui.setupUi(self) default_dir = os.getcwd() self.ui.lineEdit_choose_directory.setText(default_dir) self.ui.toolButton_choose_directory.clicked.connect(self.toolButton_choose_directory) self.ui.radioButton_search.setChecked(True) self.ui.pushButton_execute.clicked.connect(self.pushButton_execute) self.ui.listWidget_show_dst_files.setSortingEnabled(True) self.ui.label_notification.setStyleSheet("QLabel{color: black;}") self.ui.lineEdit_choose_directory.editingFinished.connect(self.handle_lineEdit_choose_directory) self.ui.lineEdit_extension.textEdited.connect(self.handle_lineEdit_extension) self.ui.lineEdit_suffix.textEdited.connect(self.handle_lineEdit_suffix) self.ui.lineEdit_search_word.textEdited.connect(self.handle_lineEdit_search_word) self.ui.lineEdit_replace_word.textEdited.connect(self.handle_lineEdit_replace_word) def handle_lineEdit_choose_directory(self): if self.ui.lineEdit_choose_directory.text() == "": self.ui.lineEdit_choose_directory.setStyleSheet("QLineEdit{border: 2px solid #e91e63; border-radius: 4px;}") else: self.ui.lineEdit_choose_directory.setStyleSheet("QLineEdit{border: 2px solid #8bc34a; border-radius: 4px;}") def handle_lineEdit_extension(self): if self.ui.lineEdit_extension.text() == "": self.ui.lineEdit_extension.setStyleSheet("QLineEdit{border: 2px solid #e91e63; border-radius: 4px;}") else: self.ui.lineEdit_extension.setStyleSheet("QLineEdit{border: 2px solid #8bc34a; border-radius: 4px;}") def handle_lineEdit_suffix(self): if self.ui.lineEdit_suffix.text() == "": self.ui.lineEdit_suffix.setStyleSheet("QLineEdit{border: 2px solid #e91e63; border-radius: 4px;}") else: self.ui.lineEdit_suffix.setStyleSheet("QLineEdit{border: 2px solid #8bc34a; border-radius: 4px;}") def handle_lineEdit_search_word(self): pass if self.ui.lineEdit_search_word.text() == "": self.ui.lineEdit_search_word.setStyleSheet("QLineEdit{border: 2px solid #e91e63; border-radius: 4px;}") else: self.ui.lineEdit_search_word.setStyleSheet("QLineEdit{border: 2px solid #8bc34a; border-radius: 4px;}") def handle_lineEdit_replace_word(self): if self.ui.lineEdit_replace_word.text() == "": self.ui.lineEdit_replace_word.setStyleSheet("QLineEdit{border: 2px solid #e91e63; border-radius: 4px;}") else: self.ui.lineEdit_replace_word.setStyleSheet("QLineEdit{border: 2px solid #8bc34a; border-radius: 4px;}") def toolButton_choose_directory(self,*args): directory = self.fileDialogMod() self.ui.lineEdit_choose_directory.setText(directory) def fileDialogMod(self): dialog = QtGui.QFileDialog() dialog.setFileMode(QtGui.QFileDialog.Directory) dialog.setOption(QtGui.QFileDialog.ShowDirsOnly) directory = dialog.getExistingDirectory(self, "対象フォルダを選択", os.path.curdir) return directory def pushButton_execute(self,*args): if self.ui.radioButton_regex.isChecked(): isRegularExpression = True else: isRegularExpression = False if self.ui.lineEdit_suffix.text() == "": self.ui.label_notification.setStyleSheet("QLabel{color: #e91e63;}") self.ui.label_notification.setText("接尾辞が入力されていません。") else: dst_directory_suffix = self.ui.lineEdit_suffix.text() if self.ui.lineEdit_extension.text() == "": self.ui.label_notification.setStyleSheet("QLabel{color: #e91e63;}") self.ui.label_notification.setText("拡張子が入力されていません。") else: target_extension = self.ui.lineEdit_extension.text() if self.ui.lineEdit_replace_word.text() == "": self.ui.label_notification.setStyleSheet("QLabel{color: #e91e63;}") self.ui.label_notification.setText("置換語句が入力されていません。") else: replace_word = self.ui.lineEdit_replace_word.text() if self.ui.lineEdit_search_word.text() == "": self.ui.label_notification.setStyleSheet("QLabel{color: #e91e63;}") self.ui.label_notification.setText("検索語句が入力されていません。") else: search_word = self.ui.lineEdit_search_word.text() if self.ui.lineEdit_choose_directory.text() == "": self.ui.label_notification.setStyleSheet("QLabel{color: #e91e63;}") self.ui.label_notification.setText("対象フォルダが選択されていません。") elif not os.path.exists(self.ui.lineEdit_choose_directory.text()): self.ui.label_notification.setText("対象フォルダが存在していません。") else: src_directory = self.ui.lineEdit_choose_directory.text() if not self.ui.lineEdit_choose_directory.text() == "" \ and os.path.exists(self.ui.lineEdit_choose_directory.text()) \ and not self.ui.lineEdit_extension.text() == "" \ and not self.ui.lineEdit_suffix.text() == "" \ and not self.ui.lineEdit_search_word.text() == "" \ and not self.ui.lineEdit_replace_word.text() == "": self.replace_text(src_directory, target_extension, dst_directory_suffix, isRegularExpression, search_word,replace_word) def build_dir_list(self, directory): dir_list = [] for root, dirs, files in os.walk(directory): for file in files: if not root in dir_list: dir_list.append(root) return dir_list def build_file_list(self, directory, extension): target_extension = extension file_list = [] for root, dirs, files in os.walk(directory): for file in files: nam, ext = os.path.splitext(file) if ext.lower() == target_extension: file = nam+ext file_list.append(os.path.join(root, file)) return file_list def create_dst_dir_list(self, directory, dir_list, suffix): src_directory = directory dst_directory_suffix = suffix src_dir_list = dir_list dst_dir_list = [] for dir in src_dir_list: dir = dir.replace(src_directory, src_directory+dst_directory_suffix) dst_dir_list.append(dir) return dst_dir_list def create_dst_file_list(self, directory, file_list, suffix): src_directory = directory dst_directory_suffix = suffix src_file_list = file_list dst_file_list = [] for file in src_file_list: file = file.replace(src_directory, src_directory+dst_directory_suffix) dst_file_list.append(file) return dst_file_list def make_directory_if_not_exists(self, dir_list): for dir in dir_list: if not os.path.exists(dir): os.makedirs(dir) def replace_text(self, directory, extension, suffix, regex, str1, str2): self.ui.listWidget_show_dst_files.clear() src_directory = directory target_extension = "."+extension dst_directory_suffix = suffix isRegularExpression = regex search_word = str1 replace_word = str2 src_dir_list = self.build_dir_list(src_directory) dst_dir_list = self.create_dst_dir_list(src_directory, src_dir_list, dst_directory_suffix) self.make_directory_if_not_exists(dst_dir_list) src_file_list = self.build_file_list(src_directory, target_extension) dst_file_list = self.create_dst_file_list(src_directory, src_file_list, dst_directory_suffix) file_dict = dict(zip(src_file_list, dst_file_list)) progress = 0 for file in src_file_list: encoding = chardet.detect(open(file, "rb").read())["encoding"] with codecs.open(file, "r", encoding) as src_file,\ codecs.open(file_dict[file], "w", encoding) as dst_file: src_lines = src_file.readlines() dst_lines = [] for line in src_lines: if isRegularExpression: line = re.sub(search_word, replace_word, line) else: line = line.replace(search_word, replace_word) dst_lines.append(line) else: dst_file.write("".join(dst_lines)) progress += 1 self.ui.listWidget_show_dst_files.addItem(os.path.basename(file)) self.ui.progressBar.setValue(round(progress/len(src_file_list)*100)) self.ui.label_notification.setStyleSheet("QLabel{color: #8bc34a;}") self.ui.label_notification.setText("テキスト置換が完了しました!")