def get_all_poems(): time_start = time.time() file_idioms = open("result/poems.txt", 'w', encoding='utf8') url = poem_base_url html = my_open(url) bsobj = html2dom(html) radicals = get_radicals(bsobj) radical_urls = get_radical_urls(radicals, idiom_base_url) chars = get_char_index_url_suffix(radical_urls, cy_referer) char_urls = get_char_urls(chars) char_url_num = len(char_urls) print("start scraping idioms at time {}".format(round(time.time()-time_start))) thread_num = 4 batch_num = char_url_num // thread_num threads = [] for m in range(thread_num): if m == thread_num - 1: urls = char_urls[m*batch_num:] else: urls = char_urls[m*batch_num:(m+1)*batch_num] t = MyThread(threadID=m, name="Thread-"+str(m), urls=urls, func=get_idioms) t.start() threads.append(t) for thread in threads: thread.join() # 这个线程完成之后,才执行下面的代码 for idiom in thread.all_words: print(idiom, file=file_idioms) file_idioms.close() print("finished at time {}".format(round(time.time()-time_start)))
def run(self): thread_data = MyThread(self.data_worker) thread_data.start() if self.bulk_num == 0: # 单条提交数据 self.one_worker() else: # bulk 提交数据 self.bulk_worker()
def get_matrix_b_block(self, start_row, start_column, end_row, end_column): """ access node's datastore to get the elements [from start_row][start_column] to [end_row][end_column] - for matrix b @return: the matrix with all the values between this limits """ thread = MyThread(self, start_row, start_column, end_row, end_column, 'b') thread.start() thread.join() return thread.block pass
def get_matrix_a_block(self, start_row, start_column, end_row, end_column): """ access node's datastore to get the elements [from start_row][start_column] to [end_row][end_column] - for matrix a @return: the matrix with all the values between this limits """ thread = MyThread(self, start_row, start_column, end_row, end_column, 'a') thread.start() thread.join() """ returns the matrix saved in thread's variable - block """ return thread.block pass
def run(self): # start first thread thread = MyThread(self.settings) thread.start() self.threadList.append(thread) self.currentThread = thread while True: # remove not working thread from thread list for i in range(len(self.threadList)): if not self.threadList[i].is_working: self.threadList.remove(i) self.activeThread = self.activeThread - 1 # set active thread count self.activeThread = len(self.threadList) # if active thread count is less than max thread count and current thread signed,not main thread stopped, then start new thread if (self.activeThread < self.settings['MAX_ACTIVE_THREAD']) and ( self.currentThread.is_signed) and not self.stopped: thread = MyThread(self.settings) thread.start() self.threadList.append(thread) self.activeThread = self.activeThread + 1 self.currentThread = thread # wait for one second time.sleep(1)
def main(): nfuncs = range(len(funcs)) print '*** SINGLE THREAD' for i in nfuncs: print 'starting', funcs[i].__name__, 'at:', \ ctime() # print 'thread_num:', activeCount() print 'thread:', current_thread() print funcs[i](n) print funcs[i].__name__, 'finished at:', \ ctime() print '\n*** MULTIPLE THREADS' threads = [] for i in nfuncs: t = MyThread(funcs[i], (n, ), funcs[i].__name__) threads.append(t) for i in nfuncs: threads[i].start() # print 'thread_num:', activeCount() print 'thread:', current_thread() for i in nfuncs: threads[i].join() print threads[i].getResults() print 'all DONE'
def get_all_zis(): """ 总共有38608个字 常用字10630 """ time_start = time.time() file_zi_detail = open("result/zi_details.json", 'w') url = zi_base_url html = my_safe_open(url) bsobj = html2dom(html) radicals = get_radicals(bsobj) radical_urls = get_radical_urls(radicals, zi_base_url) zis = get_zis(radical_urls, zi_referer) zi_urls = get_zi_urls(zis) #zi_urls = zi_urls[:100] zi_urls = zi_urls zi_url_num = len(zi_urls) print("start scraping zi at time {}".format(round(time.time()-time_start))) thread_num = 4 batch_num = zi_url_num // thread_num threads = [] for m in range(thread_num): if m == thread_num - 1: urls = zi_urls[m*batch_num:] else: urls = zi_urls[m*batch_num:(m+1)*batch_num] t = MyThread(threadID=m, name="Thread-"+str(m), urls=urls, func=get_zi_detail) t.start() threads.append(t) all_zis = dict() for thread in threads: thread.join() # 这个线程完成之后,才执行下面的代码 for item in thread.results: all_zis[item['zi_char']] = item json.dump(all_zis, file_zi_detail, ensure_ascii=False, indent='\t') file_zi_detail.close()
def compare(self, data): """ 比对配置文件是否有此数据的 key """ key = data['name'] ip = data['ip'] if key in self.conf: logger.info("%s did not respond!" % ip) # 判断是否在配置列表里面 if ip not in self.conf[key]: logger.info("%s %s isn't in command config file!" % (key, ip)) return username = self.conf[key][ip][0] password = self.conf[key][ip][1] path = self.conf[key][ip][2] logger.info("Create thread to %s Command" % ip) thread = MyThread(self.command, (ip, username, password, path, logger)) thread.start()
def get_all_words_multi_threading(): """ thread_num 2 cost time 414-27=387 thread_num 3 cost time 321-16=305 thread_num 4 cost time 309-26=283 thread_num 5 cost time 314-28=286 thread_num 8 cost time 313-26=287 thread_num 16 cost time 304-22=282 """ time_start = time.time() fwords = open("result/words3.txt", 'w', encoding='utf8') url = word_base_url html = my_open(url) bsobj = html2dom(html) radicals = get_radicals(bsobj) radical_urls = get_radical_urls(radicals, word_base_url) chars = get_char_index_url_suffix(radical_urls) char_urls = get_char_urls(chars) char_url_num = len(char_urls) print("start scraping words at time {}".format(round(time.time()-time_start))) thread_num = 2 batch_num = char_url_num // thread_num threads = [] for m in range(thread_num): if m == thread_num - 1: urls = char_urls[m*batch_num:] else: urls = char_urls[m*batch_num:(m+1)*batch_num] t = MyThread(threadID=m, name="Thread-"+str(m), urls=urls) t.start() threads.append(t) for thread in threads: thread.join() # 这个线程完成之后,才执行下面的代码 for word in thread.all_words: print(word, file=fwords) print("finished at time {}".format(round(time.time()-time_start)))
def get_all_idiom_details(): time_start = time.time() file_idioms = open("result/idiom_details.json", 'w', encoding='utf8') url = idiom_base_url html = my_open(url) bsobj = html2dom(html) radicals = get_radicals(bsobj) radical_urls = get_radical_urls(radicals, idiom_base_url) chars = get_char_index_url_suffix(radical_urls, cy_referer) char_index_urls = get_char_urls(chars) idiom_urls = get_idiom_urls(char_index_urls[0:1]) idiom_url_num = len(idiom_urls) print("start scraping idioms at time {}".format(round(time.time()-time_start))) thread_num = 4 batch_num = idiom_url_num // thread_num threads = [] for m in range(thread_num): if m == thread_num - 1: urls = idiom_urls[m*batch_num:] else: urls = idiom_urls[m*batch_num:(m+1)*batch_num] t = MyThread(threadID=m, name="Thread-"+str(m), urls=urls, func=get_idiom_detail) t.start() threads.append(t) all_idiom_details = dict() for thread in threads: thread.join() # 这个线程完成之后,才执行下面的代码 for item in thread.results: if item['name'] in all_idiom_details.keys(): print(item['name']) all_idiom_details[item['name']] = item json.dump(all_idiom_details, file_idioms, ensure_ascii=False, indent='\t') file_idioms.close() print("finished at time {}".format(round(time.time()-time_start)))
def _main(): nloops = randint(2, 5) q = Queue(32) threads = [] for i in nfuncs: t = MyThread(funcs[i], (q, nloops), funcs[i].__name__) threads.append(t) for i in nfuncs: threads[i].start() for i in nfuncs: threads[i].join()
def main(): exitIt = False threads = [] sourceIp = "10.0.0.1" destIp = "192.168.43.1" port = 33455 numberOfThreads = 5 if len(sys.argv) < 5: pass else: for i in range(4): if i == 1: sourceIp = sys.argv[1] elif i == 2: destIp = sys.argv[2] elif i == 3: try: numberOfThreads = int(sys.argv[3]) except: print("Error parsing thread number") elif i == 4: try: port = int(sys.argv[4]) except: print("Error parsing port number") for i in range(numberOfThreads): thread = MyThread(synFlood, (sourceIp, destIp, port), i, "thread-" + str(i)) threads.append(thread) print("\nDDOS attack " + destIp + ":" + str(port) + "\n") for i in range(len(threads)): threads[i].start() # threads[i].join() # print("End of attack") while exitIt == False: try: # print("waiting") sleep(0.1) except KeyboardInterrupt: confirmation = input("y/n?\n") #print(confirmation) if confirmation == "y": exitIt = True elif confirmation == "n": pass else: pass for i in range(len(threads)): threads[i].stop()
def _main(): nloops = randint(2, 5) q = Queue(100) threads = [] for i in nfuncs: tid = MyThread(funcs[i], (q, nloops), funcs[i].__name__) threads.append(tid) for i in nfuncs: threads[i].start() for i in nfuncs: threads[i].join() print("All done")
def multiple_download_pic(self,offsetlist): threads = [] for i in offsetlist: offset = i * self.count t = MyThread(func=self.download_pic_once,args=(offset,),name=i + 1) threads.append(t) for t in threads: t.start() for t in threads: t.join()
def __init__(self, parent = None): QtGui.QWidget.__init__(self, parent) self.setupUi(self) self.title = "Combinatorics - Обчислення комбінацій та перестановок" self.currentTabText = self.tabComb.tabText(self.tabComb.currentIndex()) self.currentTab = self.tabComb.currentWidget() self.setWindowTitle(self.title + " - " + self.currentTabText) self.m = ModelMetadata() #self.v = self self.timer = MyTimer(self) self.thread = MyThread(self) self.status = "stoped" self.handleEvents() self.MetaTableReset() self.metaRows["result"].setText(os.path.abspath(self.m.file.name)) self.tableMetadata.resizeColumnsToContents() self.show()
def main(): nfuncs = range(len(funcs)) print('***单线程***') for i in nfuncs: print('starting',funcs[i].__name__,'at:',ctime()) print(funcs[i](n)) #运行函数 print(funcs[i].__name__,'finished at:',ctime()) print('\n***多线程***') threads = [] for i in nfuncs: t = MyThread(funcs[i],(n,),funcs[i].__name__) #创建线程 threads.append(t) for i in nfuncs: threads[i].start() #同步开始线程 for i in nfuncs: threads[i].join() print(threads[i].getResult()) #返回线程的结果 print('all Done')
#! /usr/bin/env python3 from mythread import MyThread for i in range(10): print("i = ", i) t1 = MyThread() t2 = MyThread() t1.start() t2.start()
class Controller(QtGui.QWidget, View): def __init__(self, parent = None): QtGui.QWidget.__init__(self, parent) self.setupUi(self) self.title = "Combinatorics - Обчислення комбінацій та перестановок" self.currentTabText = self.tabComb.tabText(self.tabComb.currentIndex()) self.currentTab = self.tabComb.currentWidget() self.setWindowTitle(self.title + " - " + self.currentTabText) self.m = ModelMetadata() #self.v = self self.timer = MyTimer(self) self.thread = MyThread(self) self.status = "stoped" self.handleEvents() self.MetaTableReset() self.metaRows["result"].setText(os.path.abspath(self.m.file.name)) self.tableMetadata.resizeColumnsToContents() self.show() def run(self): sys.exit(app.exec_()) def closeEvent(self, event): # clean garbage if self.status in ["started", "paused"]: self.handleStop() # stop thread del self.m # close file event.accept() def handleEvents(self): # enable/disable spinBox or plainTextEdit self.connect(self.radioN, QtCore.SIGNAL("toggled(bool)"), self.spinN.setEnabled) self.connect(self.radioNCustom, QtCore.SIGNAL("toggled(bool)"), self.plainNCustom.setEnabled) self.tabComb.currentChanged.connect(self.handleChangeTab) # link in QLabel leads to other Tab within QTabWidget self.label.linkActivated.connect(lambda link: self.tabComb.setCurrentIndex(int(link[4:]))) # prevent setting K larger than N # self.spinN.valueChanged.connect(lambda value: self.spinK.setMaximum(value)) self.spinColumns.valueChanged["int"].connect(lambda val: setattr(self.m, "columns", val)) self.tabComb.currentChanged.connect(self.handleChange) self.plainNCustom.textChanged.connect(self.handleChange) self.spinN.valueChanged.connect(self.handleChange) self.spinK.valueChanged.connect(self.handleChange) self.radioN.clicked.connect(self.handleChange) self.radioNCustom.clicked.connect(self.handleChange) self.btnStart.clicked.connect(self.handleStart) self.btnStop.clicked.connect(self.handleStop) self.btnResultPath.clicked.connect(self.handleChangePath) self.metaRows["btnClear"].clicked.connect(self.handleClearResult) self.tableMetadata.cellDoubleClicked.connect(self.openResult) self.connect(self.timer, QtCore.SIGNAL("upd_prog_bar(int)"), self.metaRows["progressBar"], QtCore.SLOT("setValue(int)")) self.thread.finished.connect(self.handleStop) def handleChange(self): if self.plainNCustom.isEnabled(): self.m.seq = self.plainNCustom.toPlainText().split() if not self.m.seq: return #self.spinK.setMaximum(len(self.m.seq)) # if k can't be larger than N else: self.m.seq = range(1, self.spinN.value() + 1) self.m.K = self.spinK.value() self.MetaAllUpdate() def handleChangeTab(self, index): self.currentTabText = self.tabComb.tabText(index) self.currentTab = self.tabComb.widget(index) self.setWindowTitle(self.title + " - " + self.currentTabText) self.spinK.setDisabled(index==4) # Permutation doesn't require K, only N self.MetaTableReset() def disabledWhenStart(self, flag): # list of elements that gonna be disabled when Calc. starts (and enabled when stops) disableList = [self.tabComb, self.groupInput, self.checkMetadata, self.checkShowResult, self.spinColumns, self.btnResultPath, self.metaRows["btnClear"]] self.btnStop.setEnabled(flag) for w in disableList: w.setDisabled(flag) def handleStart(self): if self.status in ["stoped", "paused"]: if self.status == "stoped": self.writeMetaData() self.status = "started" self.disabledWhenStart(True) self.btnStart.setText("Призупинити") self.btnStart.setIcon(QtGui.QIcon(QtGui.QPixmap(":/icons/pause.png"))) self.timer.start(1000) self.thread.func = self.currentTab.coreGenerator self.thread.start() elif self.status == "started": self.status = "paused" self.btnStart.setText("Продовжити") self.btnStart.setIcon(QtGui.QIcon(QtGui.QPixmap(":/icons/play.png"))) self.handlePause() def handlePause(self): self.timer.stop() if self.checkShowResult.isChecked(): self.openResult() def handleStop(self): self.status = "stoped" self.disabledWhenStart(False) self.btnStart.setText("Старт обчислень") self.btnStart.setIcon(QtGui.QIcon(QtGui.QPixmap(":/icons/play.png"))) if self.timer.isActive(): self.timer.stop() self.MetaTimeUpdate() # adjustment meta data self.flushResult() if self.checkShowResult.isChecked(): self.openResult() self.m.reset() def handleChangePath(self): path = QtGui.QFileDialog.getSaveFileName(parent=self, caption="Виберіть новий файл, для збереження результату", directory=QtCore.QDir.currentPath(), filter="Text files (*.txt)") if path[0]: self.m.filename = path[0] self.m.file.close() self.m.file = open(os.path.normpath(self.m.filename), "w+", encoding="utf8") self.metaRows["result"].setText(os.path.abspath(self.m.file.name)) self.tableMetadata.resizeColumnsToContents() def handleClearResult(self): self.m.file.close() self.m.file = open(self.m.filename, "w+", encoding="utf-8") self.metaRows["labelSize"].setText("0 байт") # periodically write data from result list to file def flushResult(self): i=0 columns = self.m.columns result = "" while i<len(self.m.result): result += "\t".join(self.m.result[i : (i+columns)]) + "\n" i += columns self.m.file.write(result) self.m.file.flush() self.MetaFileSizeUpdate() self.m.result = [] def openResult(self, row=6, col=0): # row and col here recieves from table's cell dblClick signal if row==6 and col==0: os.startfile(os.path.abspath(self.m.file.name)) # os.popen("notepad " + os.path.abspath(self.m.file.name)) # could be that variant as well def writeMetaData(self): if self.checkMetadata.isChecked(): meta = "{0}\n{0}\n\nТип: {1}\nВхідні дані: N={2}{3}\nВсього комбінацій: {4}\n{0}\n".format( "-"*40, self.currentTabText, len(self.m.seq), ", k=%s" % self.spinK.value() if self.tabComb.currentIndex != 4 else "", self.m.All ) self.m.file.write(meta) self.m.file.flush() def MetaTableReset(self): self.metaRows["name"].setText(self.currentTabText) self.metaRows["all"].setText("1") self.metaRows["complete"].setText("0") self.metaRows["progressBar"].setValue(0) self.metaRows["time"].setText("") self.metaRows["left"].setText("") self.tableMetadata.resizeColumnsToContents() def MetaAllUpdate(self): try: self.m.All = self.currentTab.coreNumber(self.m.seq, self.m.K) except ValueError: self.m.All = 0 self.metaRows["all"].setText( str(self.m.All) ) self.tableMetadata.resizeColumnsToContents() def MetaTimeUpdate(self): self.metaRows["time"].setText( self.m.time ) self.metaRows["left"].setText( self.m.left ) self.metaRows["complete"].setText( str(self.m.complete) ) if self.m.complete == self.m.All: self.metaRows["progressBar"].setValue(100) self.tableMetadata.resizeColumnsToContents() def MetaFileSizeUpdate(self): size = os.stat(os.path.abspath(self.m.filename)).st_size # get size of the file in bytes l_size = list(str(size)) for i in range(len(l_size)-3, 0, -3): # insert space in each 3rd position from the end l_size.insert(i, " ") # 12345678 -> 12 345 678 self.metaRows["labelSize"].setText("".join(l_size) + " байт" )
class NetWidget(QWidget): def __init__(self,parent = None): super(NetWidget,self).__init__(parent) self.setStyleSheet("font-size : 16px")#设置整体的字体大小 self.auto = False self.pro = QProcess(self) # self.tipDlg = TipDialog() # self.tipDlg.setModal(True)#引入tipdlg,并且将这个窗口设置为最前端窗口,且后面窗口无法操作 #初始化comBox控件,并且为其添加选项 self.comBox = QComboBox() self.comBox.setFixedWidth(120) self.comBox.insertItem(0, self.tr("ping")) self.comBox.insertItem(1, self.tr("ifconfig")) self.comBox.insertItem(2, self.tr("display")) #self.comBox.insertItem(3, self.tr("traceroute")) self.comBox.insertItem(4, self.tr("top")) self.connect(self.comBox, SIGNAL('activated(QString)'),self.onActivated)#设置combBox为活动的,与函数关联 """ #初始话控件设置 #lineEdit,固定长度 #runButton,显示字符串,信号量 #pingLabel,当前显示字符 #textBrower """ self.lineEdit = QLineEdit() self.lineEdit.setContextMenuPolicy(Qt.NoContextMenu) self.lineEdit.setFixedWidth(250) self.runButton = QPushButton(self.tr("Run")) self.runButton.setStyleSheet("background: rgb(7,87,198); color: white; width: 70px; height: 20px;font-size : 16px;") self.connect(self.runButton, SIGNAL("clicked()"),self.runButton_clicked) self.pingLabel = QLabel()#初始话,之后在函数操作中会改变 self.pingLabel.setText(self.tr("Tip:please input the IP address of pinging,then get the result with clicking the button")) self.textBrowser = QTextBrowser() """ #布局一上,横向布局 #将comBox,lineEdit,runButton添加到布局中 #设置前面空为20和后面空为280 """ hLayout1 = QHBoxLayout() hLayout1.addSpacing(20) hLayout1.addWidget(self.comBox) hLayout1.addWidget(self.lineEdit) hLayout1.addWidget(self.runButton) #hLayout1.addStretch() hLayout1.addSpacing(280) #布局二中,横向布局 #将pingLabel添加到布局中,并且诶设置前面的空白为20 hLayout2 = QHBoxLayout() hLayout2.addSpacing(20) hLayout2.addWidget(self.pingLabel) #布局三下 #将textBrower添加爱到布局中,并且设置前面空白为20,后面空白为60,控件的大小自适应 hLayout3 = QHBoxLayout() hLayout3.addSpacing(20) hLayout3.addWidget(self.textBrowser) hLayout3.addSpacing(60) #主题布局总,纵向布局 #将之上的三个布局添加到总布局中,并且设置布局间空间为20,最下面的空白为40 mainLayout = QVBoxLayout() mainLayout.addSpacing(20) mainLayout.addLayout(hLayout1) mainLayout.addSpacing(20) mainLayout.addLayout(hLayout2) mainLayout.addSpacing(20) mainLayout.addLayout(hLayout3) mainLayout.addSpacing(40) self.setLayout(mainLayout) self.thread = MyThread() self.connect(self.thread,SIGNAL("getoutput"),self.append) def append(self,actionType): self.textBrowser.clear() self.textBrowser.append(actionType) #cursor = QTextCursor() #self.runButton.setText(self.tr("Stop")) cursor = self.textBrowser.textCursor() cursor.movePosition(QTextCursor.Start) self.textBrowser.setTextCursor(cursor) #changeLabel = QLabel() def onActivated(self): language = StoreInfoParser.instance().getLanguage() m_pTranslator = QTranslator() exePath = "./" if language == "chinese": QmName = "zh_CN.qm" else: QmName = "en_US.qm" if(m_pTranslator.load(QmName, exePath)): QCoreApplication.instance().installTranslator(m_pTranslator) """#comBox的相应函数,随着comBox中字符串的改变,分别控制pingLabel的显示,以及lineEdit和textBrower的显示清除和可用状态 #如果comBox当前的字符串文字为ping #pingLabel的文字设置为"提示:请在文本框中输入要ping的目标地址,然后点击执行获取结果",保持当前大小 #lineEdit中内容清除,设置为不可用 #textBrower清空""" if(self.comBox.currentText() == "Ping" or self.comBox.currentText() == "ping"): self.pingLabel.setText(self.tr("Tip:please input the IP address of pinging,then get the result with clicking the button")) self.pingLabel.adjustSize() self.lineEdit.clear() self.lineEdit.setDisabled(False) self.textBrowser.clear() #如果comBox当前的字符串文字为ifconfig #类上所说 elif(self.comBox.currentText() == "ifconfig"): self.pingLabel.setText(self.tr("Tip:get the net information")) self.pingLabel.adjustSize() self.lineEdit.clear() self.lineEdit.setEnabled(False) self.textBrowser.clear() #如果comBox当前的字符串文字为display elif(self.comBox.currentText() == "display"): self.pingLabel.setText(self.tr("Tip:get the resolution information")) self.pingLabel.adjustSize() self.lineEdit.clear() self.lineEdit.setEnabled(False) self.textBrowser.clear() elif(self.comBox.currentText() == "top"): self.pingLabel.setText(self.tr("Tip:run tom command")) self.pingLabel.adjustSize() self.lineEdit.setEnabled(False) self.lineEdit.clear() self.textBrowser.clear() #按钮的响应函数 def runButton_clicked(self): language = StoreInfoParser.instance().getLanguage() m_pTranslator = QTranslator() exePath = "./" if language == "chinese": QmName = "zh_CN.qm" else: QmName = "en_US.qm" if(m_pTranslator.load(QmName, exePath)): QCoreApplication.instance().installTranslator(m_pTranslator) #self.pro = QProcess(self)#外部程序使用声明 desktop = QApplication.desktop()#获得桌面 self.textBrowser.clear()#清除 cmdstr = QString() center = QString() goal = QString() #comBox当前text为ping if (self.comBox.currentText() == "Ping" or self.comBox.currentText() == "ping"): if (self.runButton.text() == self.tr("Run")) : center = self.lineEdit.text().trimmed() if not center: InfoHintDialog(self.tr("please input the IP address")).exec_() # self.tipDlg.setTip(self.tr("请输入ping地址!!!")) # self.tipDlg.show() # self.tipDlg.move((desktop.width()-self.tipDlg.width())/2,(desktop.height()-self.tipDlg.height())/2) self.runButton.setText(self.tr("Run")) else: self.comBox.setDisabled(True) self.pro = QProcess(self) self.runButton.setText(self.tr("stop ping")) cmdstr = "ping " +center self.textBrowser.clear() self.textBrowser.append(self.tr(" ping ")+center+self.tr(" result:")) else: self.comBox.setDisabled(False) self.runButton.setText(self.tr("Run")) self.pro.close() elif(self.comBox.currentText() == "ifconfig"): self.pro = QProcess(self) self.lineEdit.clear() self.lineEdit.setEnabled(False) self.textBrowser.clear() cmdstr = "ifconfig" # #如果comBox当前为traceroute # elif(self.comBox.currentText() == "traceroute"): # goal = self.lineEdit.text() # if (self.runButton.text() == u"执行"): # if( goal.isEmpty() or goal.isNull() ): # InfoHintDialog(u'请输入tracer地址:').exec_() # # self.tipDlg.setTip(self.tr("请输入tracer地址:")) # # self.tipDlg.show() # # self.tipDlg.move((desktop.width()-self.tipDlg.width())/2,(desktop.height()-self.tipDlg.height())/2) # # # #QMessageBox.information(self,self.tr("错误"),self.tr("请输入traceroute的目标地址")) # #return # else: # self.proc = QProcess(self) # #self.textBrowser.clear() # cmdstrc = "traceroute -n "+ goal # self.proc.start(cmdstrc) # self.connect(self.proc, SIGNAL("readyReadStandardOutput()"),self.readR) # self.connect(self.proc, SIGNAL("readyReadStandardError()"),self.readErrorR) # if self.proc.waitForStarted(10) == True: # self.comBox.setDisabled(True) # self.runButton.setText(self.tr("停止执行")) # else: # self.runButton.setText(self.tr("执行")) # self.comBox.setDisabled(False) # self.proc.close() # #如果comBox当前为display elif (self.comBox.currentText() == "display"): self.pro = QProcess(self) cmdstr = "../lib/ccr_jytcapi display" self.textBrowser.clear() #如果当前命令cmdstr不为空,则 elif (self.comBox.currentText() == "top"): if self.runButton.text() == self.tr("Run") : self.thread.start() self.comBox.setDisabled(True) self.runButton.setText(self.tr("stop top")) else: self.textBrowser.clear() self.thread.auto = False #self.thread.destroyed() self.comBox.setDisabled(False) self.runButton.setText(self.tr("Run")) if (cmdstr != ""): self.pro.start(cmdstr)#开启执行命令 self.connect(self.pro, SIGNAL("readyReadStandardOutput()"),self.read)#读取执行正常输出槽函数 self.connect(self.pro, SIGNAL("readyReadStandardError()"),self.readError)#执行异常槽函数 #读取控制台输出 def read(self): res = QString.fromLocal8Bit(self.pro.readAllStandardOutput()) self.textBrowser.append(res)#添加到text框 #读取错误 def readError(self): res = QString.fromLocal8Bit(self.pro.readAllStandardError()) self.textBrowser.append(res) def readR(self): res = QString.fromLocal8Bit(self.proc.readAllStandardOutput()) #self.textBrowser.clear() self.textBrowser.append(res) def readErrorR(self): res = QString.fromLocal8Bit(self.proc.readAllStandardError()) self.textBrowser.append(res) def updateWindow(self): if self.pro.isOpen(): self.pro.close() self.thread.auto = False self.comBox.setDisabled(False) self.comBox.setCurrentIndex(0) self.runButton.setText((self.tr("Run"))) self.pingLabel.setText(self.tr("Tip:please input the IP address of pinging,then get the result with clicking the button")) self.textBrowser.clear()
def __init__(self,parent = None): super(NetWidget,self).__init__(parent) self.setStyleSheet("font-size : 16px")#设置整体的字体大小 self.auto = False self.pro = QProcess(self) # self.tipDlg = TipDialog() # self.tipDlg.setModal(True)#引入tipdlg,并且将这个窗口设置为最前端窗口,且后面窗口无法操作 #初始化comBox控件,并且为其添加选项 self.comBox = QComboBox() self.comBox.setFixedWidth(120) self.comBox.insertItem(0, self.tr("ping")) self.comBox.insertItem(1, self.tr("ifconfig")) self.comBox.insertItem(2, self.tr("display")) #self.comBox.insertItem(3, self.tr("traceroute")) self.comBox.insertItem(4, self.tr("top")) self.connect(self.comBox, SIGNAL('activated(QString)'),self.onActivated)#设置combBox为活动的,与函数关联 """ #初始话控件设置 #lineEdit,固定长度 #runButton,显示字符串,信号量 #pingLabel,当前显示字符 #textBrower """ self.lineEdit = QLineEdit() self.lineEdit.setContextMenuPolicy(Qt.NoContextMenu) self.lineEdit.setFixedWidth(250) self.runButton = QPushButton(self.tr("Run")) self.runButton.setStyleSheet("background: rgb(7,87,198); color: white; width: 70px; height: 20px;font-size : 16px;") self.connect(self.runButton, SIGNAL("clicked()"),self.runButton_clicked) self.pingLabel = QLabel()#初始话,之后在函数操作中会改变 self.pingLabel.setText(self.tr("Tip:please input the IP address of pinging,then get the result with clicking the button")) self.textBrowser = QTextBrowser() """ #布局一上,横向布局 #将comBox,lineEdit,runButton添加到布局中 #设置前面空为20和后面空为280 """ hLayout1 = QHBoxLayout() hLayout1.addSpacing(20) hLayout1.addWidget(self.comBox) hLayout1.addWidget(self.lineEdit) hLayout1.addWidget(self.runButton) #hLayout1.addStretch() hLayout1.addSpacing(280) #布局二中,横向布局 #将pingLabel添加到布局中,并且诶设置前面的空白为20 hLayout2 = QHBoxLayout() hLayout2.addSpacing(20) hLayout2.addWidget(self.pingLabel) #布局三下 #将textBrower添加爱到布局中,并且设置前面空白为20,后面空白为60,控件的大小自适应 hLayout3 = QHBoxLayout() hLayout3.addSpacing(20) hLayout3.addWidget(self.textBrowser) hLayout3.addSpacing(60) #主题布局总,纵向布局 #将之上的三个布局添加到总布局中,并且设置布局间空间为20,最下面的空白为40 mainLayout = QVBoxLayout() mainLayout.addSpacing(20) mainLayout.addLayout(hLayout1) mainLayout.addSpacing(20) mainLayout.addLayout(hLayout2) mainLayout.addSpacing(20) mainLayout.addLayout(hLayout3) mainLayout.addSpacing(40) self.setLayout(mainLayout) self.thread = MyThread() self.connect(self.thread,SIGNAL("getoutput"),self.append)
def main(): socket_num = 3 ser_pi = socket(AF_INET, SOCK_STREAM) ser_esp = socket(AF_INET, SOCK_STREAM) ser_phe = socket(AF_INET, SOCK_STREAM) sockets = [ ser_pi, ser_esp, ser_phe ] ports = [ 9000,#Pi 3721,#ESP 7777 #phe ] flag_pi = False flag_esp = False flag_phone = False for i in range(socket_num): sockets[i].setsockopt(SOL_SOCKET,SO_REUSEADDR,1) sockets[i].bind(('',ports[i])) sockets[i].listen(5) threads = [] for i in range(socket_num): t = MyThread(target=connect_from,args=(sockets[i],)) threads.append(t) for i in range(socket_num): threads[i].start() threads[i].join() cli_pi, flag_pi = threads[0].get_result() cli_esp,flag_esp = threads[1].get_result() cli_phone,flag_phone = threads[2].get_result() clients = [cli_pi,cli_esp,cli_phone] while True: if flag_pi and flag_esp and flag_phone: break print('three sockets connected') known_faces = encoding_image() print ('waiting for order:') server = recvInit() for i in range(socket_num): clients[i].send(bytes('off',encoding='utf-8')) while True: data = cli_phone.recv(1024) print(data) if data == bytes('open',encoding='utf-8'): cli_pi.send(bytes('start',encoding='utf-8')) data = clients[0].recv(1024) print(data.decode('ascii')) recvImage(server) reg_result = recognize_image(data.decode('ascii'),known_faces=known_faces) print (reg_result) if reg_result: cli_esp.send(bytes('on',encoding='utf-8')) else: cli_esp.send(bytes('off',encoding='utf-8')) if data == bytes('close',encoding='utf-8'): cli_pi.send(bytes('close',encoding='utf-8')) for i in range(socket_num): clients[i].close() sockets[i].close() break
def run(self): thread_data = MyThread(self.data_worker) thread_data.start() if self.bulk_num == 0: # 单条提交数据 thread_es_index = MyThread(self.one_worker()) thread_es_index.start() else: # bulk 提交数据 thread_es_bulk = MyThread(self.bulk_worker()) thread_es_bulk.start()
def _get_summary_info(self): a = MyThread._get_summary_info(self) a.extend(['jobs not needed to process: {:,}'.format(self._jobs_w_end_value)]) return a
30:{"17":10000},31:{"18":4578},32:{"7":8930}, 33:{"1001433":87,"1002923":34},34:{"16":7122},35:{"27":4189}, 36:{"13":7497,"1000150":305,"1000888":49},37:{"14":9682,"1003159":454},38:{"1004179":368,"1000690":60}, 39:{"15":8403},40:{"1001544":120,"1001678":79,"1001240":130},41:{"28":5746}} loads = 0 count = 0 dict_Temp = dict() name_suf = "" thread_pools = [] #start threads for i in dict_Info: dict_Temp[i] = dict_Info[i] name_suf+=str(i)+"_" loads += 1 count += 1 if loads > 2 or count == len(dict_Info): thread = MyThread("t_"+name_suf,dict_Temp) thread.start() thread_pools.append(thread) # print "t_"+name_suf+"---"+str(dict_Temp)+"---"+str(loads) TTLog.logger.info("thread:t_"+name_suf+"started! service for"+str(dict_Temp)+"; loads:"+str(loads)) loads = 0 dict_Temp=dict() name_suf = "" #wait for all threads existing for j in thread_pools: j.join()