def test_full_paint_cycle(self): """ """ send_frame = 10 def track(): pass def paint(f): self.assertEqual(f, send_frame) def paintOverlay(qpainter): qpainter.drawRect((0, 1, 10, 5)) def shutdown(): pass def keep_running(msg_type): return msg_type != "3" result = dict() _thread.start_new(test_server.send_complete_paint, (send_frame, result)) biotracker.run_client( track, paint, paintOverlay, shutdown, keep_running=keep_running) time.sleep(5) self.assertEqual(result['qpainter'], "r(0,1,10,5)")
def run(self, nworkers): if not self.work: return # Nothing to do for i in range(nworkers - 1): thread.start_new(self._worker, ()) self._worker() self.todo.acquire()
def test_request_widgets(self): """ make sure that the widgets reach the server """ track = lambda _: None paint = lambda _: None paintOverlay = lambda _: None shutdown = lambda _: None keep_running = lambda t: t != "4" def request_widgets(): widgets = [] widgets.append(biotracker.Button('Click', lambda _: None)) widgets.append(biotracker.Divider()) return widgets result = dict() _thread.start_new(test_server.send_widget_request, (result,)) biotracker.run_client( track, paint, paintOverlay, shutdown, keep_running=keep_running, request_widgets=request_widgets) time.sleep(5) widgetsStr = result['widgets'].split(';') self.assertEqual(len(widgetsStr), 2) self.assertEqual(widgetsStr[1], "d()") btnTxt = widgetsStr[0].split(",")[1] self.assertEqual(btnTxt, "Click)")
def dispatcher(): # listen until process killed while True: # wait for next connection, connection, address = sockobj.accept() # pass to thread for service print 'Server connected by', address, print 'at', now() _thread.start_new(handleClient, (connection,))
def update_contents(self): """Update the contents of the toolbar page""" if self.have_objects_changed and self.is_active: _thread.start_new(self.update_objects_threaded, ()) elif self.is_active: self.process_object() ToolbarPage.update_contents(self)
def test_click_button_widget(self): """ request widgets + click """ counter = 0 def button_click(): nonlocal counter counter += 1 track = lambda _: None paint = lambda _: None paintOverlay = lambda _: None shutdown = lambda _: None keep_running = lambda t: t != "5" def request_widgets(): return[biotracker.Button("ClickMe", button_click)] _thread.start_new(test_server.widget_request_with_click, ()) biotracker.run_client( track, paint, paintOverlay, shutdown, keep_running=keep_running, request_widgets=request_widgets ) time.sleep(4) self.assertEqual(counter, 1) #def test_button_callback(self): """
def test_fork_with_thread(self): # XXX This test depends on a multicore machine, as busy_thread must # aquire the GIL the instant that the main thread releases it. # It will incorrectly pass if the GIL is not grabbed in time. import _thread import os import time if not hasattr(os, 'fork'): skip("No fork on this platform") def busy_thread(): print('sleep') while run: time.sleep(0) done.append(None) for i in range(5): run = True done = [] try: print('sleep') _thread.start_new(busy_thread, ()) pid = os.fork() if pid == 0: os._exit(0) else: self.timeout_killer(pid, 10) exitcode = os.waitpid(pid, 0)[1] assert exitcode == 0 # if 9, process was killed by timer! finally: run = False self.waitfor(lambda: done) assert done
def test_wait(self): for i in range(NUM_THREADS): _thread.start_new(self.f, (i,)) time.sleep(LONGSLEEP) a = sorted(self.alive.keys()) self.assertEqual(a, list(range(NUM_THREADS))) prefork_lives = self.alive.copy() if sys.platform in ['unixware7']: cpid = os.fork1() else: cpid = os.fork() if cpid == 0: # Child time.sleep(LONGSLEEP) n = 0 for key in self.alive: if self.alive[key] != prefork_lives[key]: n += 1 os._exit(n) else: # Parent self.wait_impl(cpid) # Tell threads to die self.stop = 1 time.sleep(2*SHORTSLEEP) # Wait for threads to die
def main(): if len(sys.argv) < 2: sys.stderr.write('usage: telnet hostname [port]\n') sys.exit(2) host = sys.argv[1] try: hostaddr = gethostbyname(host) except error: sys.stderr.write(sys.argv[1] + ': bad host name\n') sys.exit(2) # if len(sys.argv) > 2: servname = sys.argv[2] else: servname = 'telnet' # if '0' <= servname[:1] <= '9': port = eval(servname) else: try: port = getservbyname(servname, 'tcp') except error: sys.stderr.write(servname + ': bad tcp service name\n') sys.exit(2) # s = socket(AF_INET, SOCK_STREAM) # try: s.connect((host, port)) except error as msg: sys.stderr.write('connect failed: %r\n' % (msg,)) sys.exit(1) # thread.start_new(child, (s,)) parent(s)
def test_start(self): """ test the server-client test architecture """ send = "test123" _thread.start_new(test_server.send_str, (send,)) result = biotracker.rec_str() self.assertEqual(result, send)
def testLoadMesh(self): mesh=Mesh.createSphere(10.0,100) # a fine sphere name=tempfile.gettempdir() + os.sep + "mesh.stl" mesh.write(name) FreeCAD.Console.PrintMessage("Write mesh to %s\n"%(name)) #lock=thread.allocate_lock() for i in range(2): thread.start_new(loadFile,(name,)) time.sleep(1)
def status_update(self): # This checks if UID and Ticket number contains any value. # Then it runs the code to start the be_status_update function. if self.uid_entry.get() and self.ticket_entry.get(): _thread.start_new(caller_backend.be_status_update, (self.uid_entry.get(), self.ticket_entry.get(), self.urls)) # If the UID field OR the Ticket field are emtpy, a fun error is called. else: self.no_user_entered(ticket=True)
def __init__(self, xmpp, config): self.xmpp = xmpp self.config = config self.rest_handlers = { "room": RoomHandler(self), "participant": ParticipantHandler(self), "config": ConfigHandler(self), } self.httpd = RESTHTTPServer((config.get('rest', 'host'), config.getint('rest', 'port')), HTTPHandler, rest_handlers=self.rest_handlers, userpass=(config.get('rest', 'user'), config.get('rest', 'password'))) thread.start_new(self.process_request, tuple())
def test_track(self): """ test the track loop """ M = np.random.rand(800, 600) _thread.start_new(test_server.send_track, (8, M,)) frame, result = biotracker.recv_mat() self.assertEqual(M.shape[0], result.shape[0]) self.assertEqual(M.shape[1], result.shape[1]) self.assertEqual(frame, 8)
def test(): w = WindowOutput(queueing=flags.WQ_IDLE) w.write("First bit of text\n") import _thread for i in range(5): w.write("Hello from the main thread\n") _thread.start_new(thread_test, (w,)) for i in range(2): w.write("Hello from the main thread\n") win32api.Sleep(50) return w
def onOK(self, event, sublist, pipeline): # Once the user clicks "Run" in the derivative path file window # (from runGLA function), get the filepath and run the # "runAnalysis" function import _thread if self.box1.GetValue(): _thread.start_new(self.runAnalysis, (pipeline, sublist, self.box1.GetValue())) self.Close() else: wx.MessageBox("Please provide the path to the output directory for the pipeline you want to run group-level analysis for.")
def BeginThreadsSimpleMarshal(numThreads, cookie): """Creates multiple threads using simple (but slower) marshalling. Single interpreter object, but a new stream is created per thread. Returns the handles the threads will set when complete. """ ret = [] for i in range(numThreads): hEvent = win32event.CreateEvent(None, 0, 0, None) _thread.start_new(TestInterpInThread, (hEvent, cookie)) ret.append(hEvent) return ret
def __init__(self, pubsub): self.pubsub = pubsub self.jid = self.pubsub.config['rest']['userasjid'] self.rest_handlers = { "default": DefaultHandler(self), "node": NodeHandler(self), "subscribe": SubscribeHandler(self), "unsubscribe": UnSubscribeHandler(self), "publish": PublishHandler(self), "affiliation": AffiliationHandler(self), "test": TestHandler(self), } self.httpd = RESTHTTPServer((self.pubsub.config['rest']['server'], self.pubsub.config['rest']['port']), http_handler, rest_handlers=self.rest_handlers, userpass=(self.pubsub.config['rest']['user'], self.pubsub.config['rest']['passwd'])) thread.start_new(self.process_request, tuple())
def testAsynchronPrintFromThread(self): # http://python-kurs.eu/threads.php try: import _thread as thread, time except: import thread, time def adder(): self.count=self.count+1 # call of Console method is thread-safe FreeCAD.Console.PrintMessage("Call from Python thread (not synchronized): count="+str(self.count)+"\n") lock=thread.allocate_lock() for i in range(10): thread.start_new(adder,()) time.sleep(3) FreeCAD.Console.PrintMessage(str(self.count)+"\n")
def igtime(): global IRLTime global IRLTime_begins global IGTime_seconds global set_sun global hungry global thirsty global joueur global OFFSET IGTime_seconds = (time.time()-IRLTime_begins)*60 + 10*3600 + OFFSET time.sleep(1) if time.gmtime(IGTime_seconds)[4] == 0 or time.gmtime(IGTime_seconds)[4] == 30: joueur.hungry -=1 if 8 <= time.gmtime(IGTime_seconds)[3] <= 11 and set_sun != 1: #Gestion du soleil writeinf("The sun is rising.") set_sun = 1 if 12 <= time.gmtime(IGTime_seconds)[3] <= 19 and set_sun != 2: writeinf("The sun is high.") set_sun = 2 if 20 <= time.gmtime(IGTime_seconds)[3]<= 23 and set_sun != 3: writeinfper("The sun is setting.") set_sun = 3 if 0 <= time.gmtime(IGTime_seconds)[3] <= 7 and set_sun != 0: set_sun = 0 _thread.start_new(midnight,()) if joueur.hungry <=0 and hungry != 0: #Gestion de la faim write('You died from starvation.') hungry = 0 if 76 <= joueur.hungry <=100 and hungry !=4: write('You aren\'t hungry. What a luck !') sys.stdout.flush() hungry = 4 if 51 <= joueur.hungry <=75 and hungry !=3: write('You wouldn\'t mind having a bite of something.') sys.stdout.flush() hungry = 3 if 26 <= joueur.hungry <=50 and hungry !=2: write('You are hungry... ') sys.stdout.flush() hungry = 2 if 1 <= joueur.hungry <=25 and hungry !=1: write('Your stomach is hurting you and you feel dizzy. ') sys.stdout.flush() hungry = 1 igtime()
def testSynchronPrintFromThread(self): # http://python-kurs.eu/threads.php try: import _thread as thread, time except: import thread, time def adder(): lock.acquire() self.count=self.count+1 # call of Console method is thread-safe FreeCAD.Console.PrintMessage("Call from Python thread: count="+str(self.count)+"\n") lock.release() lock=thread.allocate_lock() for i in range(10): thread.start_new(adder,()) time.sleep(3) self.failUnless(self.count==10,"Synchronization of threads failed") FreeCAD.Console.PrintMessage(str(self.count)+"\n")
def handle_request(self): """Handle one request, possibly blocking.""" try: request, client_address = self.get_request() logging.log(logging.DEBUG, "%s request on child %s" % (self.httpstyle, os.getpid())) except socket.error: return if self.verify_request(request, client_address): busy = True while busy: with self.lock: if self.threads < self.maxthreads: busy = False if busy: logging.log(logging.DEBUG, "Max threads encountered, waiting to handle request") time.sleep(.1) with self.lock: self.threads += 1 logging.log(logging.DEBUG, "%s threads" % self.threads) #print "Starting thread" thread.start_new(self.process_request, (request, client_address))
def Start(self): self.enable = True page = self.page print (u'正在加载中请稍候......') # 新建一个线程在后台加载段子并存储 _thread.start_new(self.LoadPage,()) #----------- 加载处理糗事百科 ----------- while self.enable: # 如果self的page数组中存有元素 if self.pages: nowPage = self.pages[0] #print(len(nowPage)) del self.pages[0] print(u'第%d页' % page) self.ShowPage(nowPage,page) myInput = input() if myInput == "quit": self.enable = False continue page += 1
def startPycheckerRun(self): self.result=None old=win32api.SetCursor(win32api.LoadCursor(0, win32con.IDC_APPSTARTING)) win32ui.GetApp().AddIdleHandler(self.idleHandler) import _thread _thread.start_new(self.threadPycheckerRun,())
def info(self, text): start_new(wgfunc.TextFader.fade, (self.progress_label, text))
def __init__(self, parent): self.active_tab = "Games" self.cont_frm_id = None self.last_listbox_item_highlight = -1 self.listbox_item_height = 20 tk.Toplevel.__init__(self, parent) # Window configuration self.config(bg=BG, padx=0, pady=0) self.title("XtremeUpdater") self.transient(parent) self.overrideredirect(True) # Widgets self.head = tk.Frame(self, width=800, height=32, **frm_cnf) self.title = tk.Label(self.head, text=self.title(), **hlb_cnf) self.close = tk.Button( self.head, text="×", command=exit, **{ **btn_cnf, **btn_head_cnf }) self.minimize = tk.Button( self.head, text="-", command=parent.iconify, **{ **btn_cnf, **btn_head_cnf }) self.navigation = tk.Frame(self, **{**frm_cnf, **nav_frm_cnf}) self.tab0 = tk.Button( self.navigation, text="Games", command=lambda: self.tab_switch("Games"), **btn_nav_cnf) self.tab1 = tk.Button( self.navigation, text="Collection", command=lambda: self.tab_switch("Collection"), **btn_nav_cnf) self.tab2 = tk.Button( self.navigation, text="System", command=lambda: self.tab_switch("System"), **btn_nav_cnf) self.canvas = tk.Canvas(self, width=800, height=400, **cnv_cnf) self.games = tk.Frame(self, **cont_frm_cnf) self.dirselection = tk.Frame(self.games, **cont_frm_cnf) self.gamename = tk.Label( self.dirselection, text="Select a game directory", **lb_cnf) self.browse = tk.Button( self.dirselection, text="\u2026", command=self._browse_callback, **btn_cnf) self.dll_frame = tk.Frame(self.games, **{ **cont_frm_cnf, "padx": 0, "pady": 0, "highlightthickness": 0, "bd": 0 }) self.dll_frame_head = tk.Frame(self.dll_frame, **cont_frm_cnf) self.available_updates_label = tk.Label( self.dll_frame_head, text="Available dll updates", **seclb_cnf) self.select_all_button = tk.Button( self.dll_frame_head, text="\ue762", command=self._select_all, state='disabled', **btn_cnf) self.dll_listbox = tk.Listbox( self.dll_frame, width=90, height=13, **listbox_cnf) self.listbox_scrollbar = ttk.Scrollbar( self.dll_frame, command=self.dll_listbox.yview) self.dll_listbox.config(yscrollcommand=self.listbox_scrollbar.set) self.update_frame = tk.Frame(self.dll_frame, **{**frm_cnf, 'padx': 0}) self.update_button = tk.Button( self.update_frame, text="Update", state='disabled', command=lambda: start_new(self._update_callback, ()), **{ **btn_cnf, 'font': ('Roboto Bold', 16) }) self.progress_label = tk.Label(self.update_frame, **seclb_cnf) self.collection_frame = tk.Frame(self, **cont_frm_cnf) self.collectionlabel0 = tk.Label( self.collection_frame, text="Detected games", **seclb_cnf) self.commonpaths_listbox = tk.Listbox( self.collection_frame, width=90, height=13, **{ **listbox_cnf, 'selectmode': 'single' }) self.system = tk.Frame(self, **cont_frm_cnf) self.spectre_patch_lbframe = tk.LabelFrame( self.system, text="Spectre and Meltdown patch:", **lbfrm_cnf, width=300, height=120) self.spectre_patch_disable = tk.Button( self.spectre_patch_lbframe, text="Disable", command=None, **btn_cnf) self.spectre_patch_enable = tk.Button( self.spectre_patch_lbframe, text="Enable", command=None, **btn_cnf) self.spectrewrn_label = tk.Label( self.spectre_patch_lbframe, text= "Disabling spectre patch can exhibit you to attacks from hackers, but it can significantly improve system performance on old CPUs. By right-clicking this label you agree with that we dont have any responsibility on potentional damage caused by attackers!", **wrnlb_cnf) self.dummy_dll_list = tk.Label( self.dll_frame, text="\ue8b7\nPlease select a game directory", **biglb_cnf) self.favorite = tk.Button( self.navigation, text="\ue735", command=lambda: self.tab_switch("\ue735"), **{ **btn_nav_cnf, 'width': 1, 'font': ('Segoe MDL2 Assets', 14) }) self.favorite_frame = tk.Frame(self, **cont_frm_cnf) self.spectre_patch_lbframe.pack_propagate(False) # Widget display self.head.pack(**head_frm_pck) self.title.pack(**title_lb_pck) self.close.place(x=790, y=0, anchor='ne') self.minimize.place(x=766, y=0, anchor='ne') self.navigation.pack(**nav_frm_pck) self.tab0.pack(**btn_nav_pck) self.tab1.pack(**btn_nav_pck) self.tab2.pack(**btn_nav_pck) self.favorite.pack(**{**btn_nav_pck, 'side': 'right', 'ipadx': 20}) self.canvas.pack(**cnv_pck) # Games self.dirselection.pack(anchor='w', fill='x') self.gamename.pack(side='left', fill='x') self.browse.pack(side='right') self.dll_frame_head.pack(fill='x') self.available_updates_label.pack(side='left', anchor='w') self.select_all_button.pack(side='right') self.dll_frame.pack(fill='both', expand=True) self.dummy_dll_list.pack(fill='both', expand=True) self.update_frame.pack(side='bottom', fill='x') self.progress_label.pack(side='left') self.update_button.pack(side='right') # self.listbox_scrollbar.pack(side='left', fill='y') # Collection self.collectionlabel0.pack(anchor='w') self.commonpaths_listbox.pack(fill='both') # System self.spectre_patch_lbframe.pack(anchor="w", pady=10, padx=10) self.spectrewrn_label.pack() self.spectre_patch_disable.pack() self.spectre_patch_enable.pack() # Bindings for btn in all_children(self, 'Button'): btn.bind( "<Enter>", lambda *args, wg=btn: wgfunc.fade(wg, tuple(btn_hover_cnf_cfg.keys()), tuple(btn_hover_cnf_cfg.values())) ) btn.bind( "<Leave>", lambda *args, wg=btn: wgfunc.fade(wg, tuple(btn_normal_from_hover_cnf_cfg.keys()), tuple(btn_normal_cnf_cfg.values())) ) self.spectrewrn_label.bind( "<Button-3>", lambda *args: self.spectrewrn_label.pack_forget()) # self.dll_frame.bind("<Enter>", lambda *args: self.listbox_scrollbar.pack(side='left', fill='y')) self.dll_frame.bind("<Leave>", lambda *args: self.listbox_scrollbar.pack_forget()) self.dll_listbox.bind("<<ListboxSelect>>", lambda *args: self._update_select_button()) self.dll_listbox.bind("<Motion>", self._listbox_hover_callback) self.dll_listbox.bind("<Leave>", self._listbox_hover_callback) self.dll_listbox.bind("<MouseWheel>", self._listbox_scroll_callback) self.title.bind("<Button-1>", self._clickwin) self.title.bind("<B1-Motion>", self._dragwin) self.dummy_dll_list.bind('<Button-1>', lambda *args: self._browse_callback()) self.commonpaths_listbox.bind("<<ListboxSelect>>", self._common_path_listbox_callback) # Canvas setup self.canvas.create_image( -40, -40, image=get_img("img/acrylic_dark.png"), anchor="nw", tags="logo") self.load_common_paths() self.info("Follow the blinking buttons | Browse for a directory first") reminder.remind(self.browse)
def test_UI(root): #一些常数和错误处理# bool_ever_click_connect_button = 0 bool_is_device_connected_successful = 0 min_click_times = 1 max_click_times = 9999 min_interval_time = 0.1 max_interval_time = 99.9 min_drag_times_number = 1 max_drag_times_number = 9999 min_drag_during_time = 0.1 max_drag_during_time = 9.9 min_drag_interval_time = 0.1 max_drag_interval_time = 99.9 max_pos_x = 1000 max_pos_y = 1000 exception_count = 0 while (1): try: open('exception_' + str(exception_count) + '.txt') exception_count += 1 except IOError: break empty_error_code = 0 number_error_code = 1 logic_error_code = 2 resolution_ration_error_code = 3 something_else_error_code = 4 have_not_connect_error_code = 5 not_successful_connected_error_code = 6 def error_message_prompt(error_code): if (error_code == 0): #错误信息:空输入 tk.messagebox.showinfo('输入错误', '输入不能为空或非半角阿拉伯数字,具体输入规范可参考顶部菜单栏的“帮助”按钮') elif (error_code == 1): #错误信息:输入的应该是数字却不是 tk.messagebox.showinfo('输入错误', '请输入半角阿拉伯正数,具体输入规范可参考顶部菜单栏的“帮助”按钮') elif (error_code == 2): tk.messagebox.showinfo('输入错误', '请输入不要超过限定范围,具体输入范围可参考顶部菜单栏的“帮助”按钮') elif (error_code == 3): tk.messagebox.showinfo('输入错误', '请正确输入手机分辨率,以半角阿拉伯正数形式输入') elif (error_code == something_else_error_code): tk.messagebox.showinfo('未知错误', '发生了一些未知的错误,程序将退出') elif (error_code == have_not_connect_error_code): tk.messagebox.showinfo('提示', '请先连接设备!') elif (error_code == not_successful_connected_error_code): tk.messagebox.showinfo('连接错误', '还未成功连接设备') #常数和错误处理结束# # root = Tk() root.title("测试界面") root.geometry('1250x650') root.resizable(0, 0) # 禁止调整窗口大小 uisocket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) port = 8081 host = '127.0.0.1' def runMonkeyServer(lock): ##!!!!!!!!!!!!!!!!!!!!!!!!!!!!此位置改成MonkeyServer.py所在位置 ret = os.system( r"monkeyrunner C:\Users\Lenovo\Desktop\Autotest-master\example\MonkeyServer.py" ) '''if(ret == 0): tk.messagebox.showinfo('运行错误','无法打开monkeyrunner,请检查路径设置是否正确') ''' lock.release() lock = thread.allocate_lock() lock.acquire() thread.start_new(runMonkeyServer, (lock, )) def connect_waiting(): nonlocal bool_is_device_connected_successful connect_log = open(os.getcwd() + '\\connectlog.txt', 'r') content = connect_log.read() nonlocal connect_waiting_timer if (content == 'True'): bool_is_device_connected_successful = 1 print_text.insert('end', 'connection successful!') connect_waiting_timer.cancel() connect_log.close() else: connect_log.close() connect_waiting_timer = threading.Timer(0.5, connect_waiting) connect_waiting_timer.start() def connect(): nonlocal bool_ever_click_connect_button bool_ever_click_connect_button = 1 path = os.getcwd() print_text.insert('end', "TestMethod: waiting for connection..") send('connect', ord(path[0]), 0, 0, 0, 0, 0, 0, path[2:]) nonlocal connect_waiting_timer connect_waiting_timer = threading.Timer(0.5, connect_waiting) connect_waiting_timer.start() #send('connect',0,0,0,0,0,0,0,0) connect_waiting_timer = threading.Timer(0.5, connect_waiting) def pause(): print_text.insert('end', "TestMethod: pause") send('pause', 0, 0, 0, 0, 0, 0, 0, 0) def resume(): print_text.insert('end', "TestMethod: resume") send('resume', 0, 0, 0, 0, 0, 0, 0, 0) def stop(): print_text.insert('end', "TestMethod: stop") send('stop', 0, 0, 0, 0, 0, 0, 0, 0) def start(): log_timer = threading.Timer(1, log_monitor) log_timer.start() print_text.insert('end', "TestMethod: start") send('start', 0, 0, 0, 0, 0, 0, 0, 0) def send(optype, x1, y1, x2, y2, number, interval_time, drag_time, keyorstring): data = bytes("%s:%d:%d:%d:%d:%d:%f:%f:%s" % (optype, x1, y1, x2, y2, number, interval_time, drag_time, keyorstring), encoding="utf8") uisocket.sendto(data, (host, port)) ''' def random_touch(): touch_number = int(e_touch_number.get()) # 通过输入框获取参数 点击次数 interval_time = float(e_interval_time.get()) # 通过输入框获取参数 间隔时间 print("TestMethod: random_touch 点击次数:%d 间隔时间:%f"%(touch_number, interval_time)) send('random_touch',0,0,0,0,touch_number,interval_time,0,0) def delete_print(): nonlocal print_text print_text.delete(0,'end') ''' menubar = tk.Menu(root) # 菜单选项 def help_func(): tk.messagebox.showinfo( '帮助', '输入请输入半角阿拉伯数字,每一个输入文本框都输入完毕以后再点击确认按钮。\n\ 输入范围限制如下:\n\ 点击次数:1-9999次\n\ 间隔时间:0.1-99.9s\n\ 滑动次数:1-9999次\n\ 滑动时间:0.1-9.9s\n\ 滑动间隔时间:0.1-99.9s\n\ 点击位置不可超出app分辨率\n\ 若希望软件自动启动需要测试的游戏,请正确输入游戏的包名和活动名,留空则默认对当前运行的应用进行测试\n\ 需要修改分辨率参数,输入并再次确认即可\n\ 使用遇到问题,可发送邮件到[email protected]') #help_menu = tk.Menu(menubar, tearoff=0) menubar.add_command(label='帮助', command=help_func) root.config(menu=menubar) ## 最左边文本框输出测试队列信息 print_text = Listbox(root, bg='white', width='45', height='80') def delete_text(): nonlocal print_text print_text.delete(0, 'end') b_delete = Button(root, text='清屏', width='3', command=delete_text).pack(side='left', fill='y') print_text.pack(side='left') ## 最左边文本框输出测试队列信息 ##左侧frame## frame_left = Frame(root, bg='white', width=459, height=1200) frame_left.pack(side='left') log_name = "log.txt" exception_raw_name = 'exception.txt' exception_name = 'exception_' + str(exception_count) + '.txt' content_initialize = "开始测试后,测试报告会显示在这" scr = scrolledtext.ScrolledText(frame_left, width=65, height=1200) scr.insert('end', content_initialize) scr.pack() #label_2=Label(scr,text = content_initialize,bg = 'white',justify='left') #label_2.place(x = 0,y = 0) #os.remove(os.getcwd() + '\\' + exception_raw_name) connect_status_flag = open(os.getcwd() + '\\connectlog.txt', 'w+') #初始化connectlog.txt connect_status_flag.write("False") connect_status_flag.close() #label_test = Lab #print(os.getcwd()) #采用timer实时监测文件变化 read_log = 0 log_lines = [] bool_successful_read_log = 0 file_log = open('connectlog.txt', 'r') def log_monitor(): nonlocal log_name nonlocal read_log nonlocal log_lines nonlocal file_log nonlocal scr nonlocal bool_successful_read_log try: read_log = 1 if (not bool_successful_read_log): file_log = open(log_name, 'r') bool_successful_read_log = 1 final_line = file_log.readline() if (final_line != ''): log_lines.append(final_line) scr.insert('end', final_line) #print(log_lines) #nonlocal label_2 #label_2.config(text = content) #file_log.close() try: file_exception = open(exception_raw_name, 'r') file_exception_log = open(exception_name, 'a+') lines_count = len(log_lines) if (len(log_lines) == 0): #print('no log file') log_timer = threading.Timer(0.5, log_monitor) log_timer.start() return lines_to_be_written = [] min_lines_error_log = min(10, lines_count) for i in range(lines_count - 1, lines_count - min_lines_error_log, -1): lines_to_be_written.insert(0, log_lines[i]) file_exception_log.writelines(lines_to_be_written) scr.insert('end', '\n出现异常!相关内容已经保存到根目录下' + exception_name + '\n测试已停止') #content = content + '\n出现异常!相关内容已经保存到根目录下' + exception_name + '\n测试已停止' #label_2.config(text = content) print_text.insert('end', '出现异常!相关内容已经保存到' + exception_name) print_text.insert('end', '测试已停止') nonlocal exception_count exception_count += 1 file_exception.close() os.remove(os.getcwd() + '\\' + exception_raw_name) stop() file_log.close() file_exception_log.close() except IOError: log_timer = threading.Timer(0.5, log_monitor) log_timer.start() except IOError: if (read_log == 0): scr.insert('end', '暂未读取到日志文件') # label_2.config(text = content) '''log_timer = threading.Timer(1,log_monitor) log_timer.start()''' ##左侧frame## #连接手机按钮 b_con_phone = Button(root, text='连接设备', font=('黑体', 12), height=2, command=connect) b_con_phone.pack(fill='x', side='top') # 打开app按钮 judge_con = 0 # 判断输入信息按钮是否展开 judge_choose_test = 0 # 判断是否弹测试选择按钮是否展开 def click_b_con(): # 开始命名成了连接。。实际上此函数时展开输入app选项的按钮 nonlocal judge_choose_test nonlocal judge_con if (bool_ever_click_connect_button == 0): error_message_prompt(have_not_connect_error_code) return if (bool_is_device_connected_successful == 0): error_message_prompt(not_successful_connected_error_code) return if judge_choose_test == 0 and judge_con == 0: b_choose.forget() fm_con.pack() b_choose.pack(fill='x') judge_con = 1 fm_touch.forget() fm_r_touch.forget() fm_drag.forget() fm_r_drag.forget() elif judge_choose_test == 0 and judge_con == 1: fm_con.forget() judge_con = 0 elif judge_choose_test == 1 and judge_con == 0: b_choose.forget() fm_con.pack() b_choose.pack(fill='x') judge_con = 1 fm_choose.forget() judge_choose_test = 0 fm_touch.forget() fm_r_touch.forget() fm_drag.forget() fm_r_drag.forget() elif judge_choose_test == 1 and judge_con == 1: fm_con.forget() judge_con = 0 fm_choose.forget() judge_choose_test = 0 b_con = Button(root, text='输入需要测试的app参数', font=('黑体', 12), height=2, command=click_b_con) b_con.pack(fill='x') # 应用信息 fm_con = Frame(root) # 连接手机或模拟器的块 v_con_x = 0 # 分辨率x值,初值为0 v_con_y = 0 # 分辨率y值,初值为0 v_p_name = '' # 应用的包名 v_a_name = '' # 应用的活动名 con_x = Label(fm_con, text='分辨率x值:') con_x.pack(side='top') con_x_text = StringVar() con_x_entry = Entry(fm_con, textvariable=con_x_text) con_x_text.set("") con_x_entry.pack(side='top') con_y = Label(fm_con, text='分辨率y值:') con_y.pack(side='top') con_y_text = StringVar() con_y_entry = Entry(fm_con, textvariable=con_y_text) con_y_text.set("") con_y_entry.pack(side='top') p_name = Label(fm_con, text='应用的包名(Package Name):') p_name.pack(side='top') p_name_text = StringVar() p_name_entry = Entry(fm_con, textvariable=p_name_text) p_name_text.set("") p_name_entry.pack(side='top') a_name = Label(fm_con, text='应用的活动名(Activity Name):') a_name.pack(side='top') a_name_text = StringVar() a_name_entry = Entry(fm_con, textvariable=a_name_text) a_name_text.set("") a_name_entry.pack(side='top') def click_b_con_confirm(): nonlocal judge_con v_con_x = con_x_entry.get() v_con_y = con_y_entry.get() try: nonlocal max_pos_x nonlocal max_pos_y v_con_x = int(con_x_entry.get()) v_con_y = int(con_y_entry.get()) max_pos_x = v_con_x max_pos_y = v_con_y except ValueError: error_message_prompt(resolution_ration_error_code) v_p_name = p_name_entry.get() v_a_name = a_name_entry.get() fm_con.forget() # 点击设备信息的确定按钮之后,会暂时消除填入信息的行,再次点击‘请先点击输入设备信息’按钮之后会重新出现 judge_con = 0 # print("TestMethod: open_app") send('open_app', 0, 0, 0, 0, 0, 0, 0, v_p_name + '&' + v_a_name) nonlocal print_text print_text.delete(0, 'end') Button(fm_con, text="确定", command=click_b_con_confirm).pack(pady=5) def click_b_choose(): nonlocal judge_choose_test nonlocal judge_con if (bool_ever_click_connect_button == 0): error_message_prompt(have_not_connect_error_code) return if (bool_is_device_connected_successful == 0): error_message_prompt(not_successful_connected_error_code) return if judge_choose_test == 0 and judge_con == 0: fm_choose.pack() judge_choose_test = 1 fm_touch.forget() fm_r_touch.forget() fm_drag.forget() fm_r_drag.forget() elif judge_choose_test == 0 and judge_con == 1: fm_con.forget() judge_con = 0 fm_choose.pack() judge_choose_test = 1 fm_touch.forget() fm_r_touch.forget() fm_drag.forget() fm_r_drag.forget() elif judge_choose_test == 1 and judge_con == 0: fm_choose.forget() judge_choose_test = 0 elif judge_choose_test == 1 and judge_con == 1: fm_con.forget() judge_con = 0 fm_choose.forget() judge_choose_test = 0 def click_b_touch(): # fm_ctrl.forget() fm_choose.forget() fm_touch.pack() def click_b_r_touch(): # fm_ctrl.forget() fm_choose.forget() fm_r_touch.pack() def click_b_drag(): # fm_ctrl.forget() fm_choose.forget() fm_drag.pack() def click_b_r_drag(): # fm_ctrl.forget() fm_choose.forget() fm_r_drag.pack() fm_choose = Frame(root) b_choose = Button(root, text='选择测试类型', font=('黑体', 12), height=2, command=click_b_choose) b_choose.pack(fill='x') b_touch_test = Button(fm_choose, text='点击屏幕测试', font=('黑体', 10), height=3, command=click_b_touch) b_touch_test.pack(side='left') b_r_touch_test = Button(fm_choose, text='随机点击屏幕测试', font=('黑体', 10), height=3, command=click_b_r_touch) b_r_touch_test.pack(side='left') b_drag_test = Button(fm_choose, text='滑动屏幕测试', font=('黑体', 10), height=3, command=click_b_drag) b_drag_test.pack(side='left') b_r_drag_test = Button(fm_choose, text='随机屏幕测试', font=('黑体', 10), height=3, command=click_b_r_drag) b_r_drag_test.pack(side='left') # 点击屏幕测试 v_pos_x = 0 # 点击的位置x v_pos_y = 0 # 点击的位置y v_touch_n = 0 # 点击的次数 v_i_time = 1.00 # 多次点击时间隔时间,默认为1.00秒 fm_touch = Frame(root) # fm1.pack(side = 'left',fill = 'y') label_fm_touch = Label(fm_touch, bg='white', text='点击屏幕测试', font=('黑体', 12)) label_fm_touch.pack(fill='x', pady='5') pos_x = Label(fm_touch, text='点击的位置x:', pady=5) pos_x.pack(side='top') pos_x_text = StringVar() pos_x_entry = Entry(fm_touch, textvariable=pos_x_text) pos_x_text.set("") pos_x_entry.pack(side='top', pady=5) pos_y = Label(fm_touch, text='点击的位置y:', pady=5) pos_y.pack(side='top') pos_y_text = StringVar() pos_y_entry = Entry(fm_touch, textvariable=pos_y_text) pos_y_text.set("") pos_y_entry.pack(side='top', pady=5) touch_n = Label(fm_touch, text='点击的次数:', pady=5) touch_n.pack(side='top') touch_n_text = StringVar() touch_n_entry = Entry(fm_touch, textvariable=touch_n_text) touch_n_text.set("") touch_n_entry.pack(side='top', pady=5) i_time = Label(fm_touch, text='多次点击时间隔时间,默认为1秒:', pady=5) i_time.pack(side='top') i_time_text = StringVar() i_time_entry = Entry(fm_touch, textvariable=i_time_text) i_time_text.set("") i_time_entry.pack(side='top', pady=5) def click_b_confirm_touch(): nonlocal print_text try: v_pos_x = int(pos_x_entry.get()) v_pos_y = int(pos_y_entry.get()) v_touch_n = int(touch_n_entry.get()) v_i_time = float(i_time_entry.get()) fm_touch.forget() fm_choose.pack() logic_error = 0 if (v_pos_x < 0 or v_pos_x > max_pos_x): logic_error = 1 if (v_pos_y < 0 or v_pos_y > max_pos_y): logic_error = 1 if (v_touch_n < min_click_times or v_touch_n > max_click_times): logic_error = 1 if (v_i_time < min_interval_time or v_i_time > max_interval_time): logic_error = 1 if (logic_error == 1): error_message_prompt(logic_error_code) else: print_text.insert('end', "TestMethod: touch") print_text.insert( 'end', "点击位置:(%d,%d) 点击次数:%d 间隔时间:%f" % (v_pos_x, v_pos_y, v_touch_n, v_i_time)) send('touch', v_pos_x, v_pos_y, 0, 0, v_touch_n, v_i_time, 0, 0) except ValueError: if (pos_x_entry.get() == '' or pos_y_entry.get() == '' or touch_n_entry.get() == '' or i_time_entry.get() == ''): error_message_prompt(empty_error_code) else: error_message_prompt(number_error_code) Button(fm_touch, text="加入测试队列", command=click_b_confirm_touch).pack(pady=5) # 随机点屏幕 v_r_touch_n = 0 # 点击的次数 v_r_touch_time = 1.0 # 每两次点击间隔的时间,秒为单位 fm_r_touch = Frame(root) label_fm_r_touch = Label(fm_r_touch, bg='white', text='随机点屏幕', font=('黑体', 12)) label_fm_r_touch.pack(fill='x', pady='5') r_touch_n = Label(fm_r_touch, text='点击的次数:', pady=5) r_touch_n.pack(side='top') r_touch_n_text = StringVar() r_touch_n_entry = Entry(fm_r_touch, textvariable=r_touch_n_text) r_touch_n_text.set("") r_touch_n_entry.pack(side='top', pady=5) r_touch_time = Label(fm_r_touch, text='每两次点击间隔的时间,秒为单位:', pady=5) r_touch_time.pack(side='top') r_touch_time_text = StringVar() r_touch_time_entry = Entry(fm_r_touch, textvariable=r_touch_time_text) r_touch_time_text.set("") r_touch_time_entry.pack(side='top', pady=5) def click_b_r_touch_confirm(): nonlocal print_text try: v_r_touch_n = int(r_touch_n_entry.get()) v_r_touch_time = float( r_touch_time_entry.get()) #间隔时间 对应interval time fm_r_touch.forget() fm_choose.pack() logic_error = 0 if (v_r_touch_n < 0 or v_r_touch_n > max_click_times): logic_error = 1 if (v_r_touch_time < min_interval_time or v_r_touch_time > max_interval_time): logic_error = 1 if (logic_error == 1): error_message_prompt(logic_error_code) else: print_text.insert('end', "TestMethod: random_touch") print_text.insert( 'end', "点击次数:%d 间隔时间:%fs" % (v_r_touch_n, v_r_touch_time)) send('random_touch', 0, 0, 0, 0, v_r_touch_n, v_r_touch_time, 0, 0) except ValueError: if (r_touch_n_entry.get() == '' or r_touch_time_entry.get() == ''): error_message_prompt(empty_error_code) else: error_message_prompt(number_error_code) Button(fm_r_touch, text="加入测试队列", command=click_b_r_touch_confirm).pack(pady=5) #滑动屏幕测试 v_start_x = 0 # 滑动起始位置x v_start_y = 0 # 滑动起始位置y v_end_x = 0 # 滑动结束位置x v_end_y = 0 # 滑动结束位置y v_d_time = 1 # 滑动持续时间,默认为1秒 v_d_num = 1 # 滑动次数,默认为1次 v_d_i_time = 1.0 # 多次点击时间隔时间,默认为1秒 fm_drag = Frame(root) # fm3.pack(side = 'left',fill = 'y') label_fm_drag = Label(fm_drag, bg='white', text='滑动屏幕测试', font=('黑体', 12)) label_fm_drag.pack(fill='x', pady='2') start_x = Label(fm_drag, text='滑动起始位置x:', pady=2) start_x.pack(side='top') start_x_text = StringVar() start_x_entry = Entry(fm_drag, textvariable=start_x_text) start_x_text.set("") start_x_entry.pack(side='top', pady=5) start_y = Label(fm_drag, text='滑动起始位置y:', pady=2) start_y.pack(side='top') start_y_text = StringVar() start_y_entry = Entry(fm_drag, textvariable=start_y_text) start_y_text.set("") start_y_entry.pack(side='top', pady=5) end_x = Label(fm_drag, text='滑动结束位置x:', pady=2) end_x.pack(side='top') end_x_text = StringVar() end_x_entry = Entry(fm_drag, textvariable=end_x_text) end_x_text.set("") end_x_entry.pack(side='top', pady=5) end_y = Label(fm_drag, text='滑动结束位置y:', pady=2) end_y.pack(side='top') end_y_text = StringVar() end_y_entry = Entry(fm_drag, textvariable=end_y_text) end_y_text.set("") end_y_entry.pack(side='top', pady=5) d_time = Label(fm_drag, text='滑动持续时间,默认为1秒:', pady=2) d_time.pack(side='top') d_time_text = StringVar() d_time_entry = Entry(fm_drag, textvariable=d_time_text) d_time_text.set("") d_time_entry.pack(side='top', pady=5) d_num = Label(fm_drag, text='滑动次数,默认为1次:', pady=2) d_num.pack(side='top') d_num_text = StringVar() d_num_entry = Entry(fm_drag, textvariable=d_num_text) d_num_text.set("") d_num_entry.pack(side='top', pady=5) d_i_time = Label(fm_drag, text='多次点击时间隔时间,默认为1秒:', pady=2) d_i_time.pack(side='top') d_i_time_text = StringVar() d_i_time_entry = Entry(fm_drag, textvariable=d_i_time_text) d_i_time_text.set("") d_i_time_entry.pack(side='top', pady=5) def click_b_drag_confirm(): nonlocal print_text try: v_start_x = int(start_x_entry.get()) v_start_y = int(start_y_entry.get()) v_end_x = int(end_x_entry.get()) v_end_y = int(end_y_entry.get()) v_d_time = int(d_time_entry.get()) v_d_num = int(d_num_entry.get()) v_d_i_time = float(d_i_time_entry.get()) fm_drag.forget() fm_choose.pack() logic_error = 0 if (v_start_x < 0 or v_start_x > max_pos_x): logic_error = 1 if (v_start_y < 0 or v_start_y > max_pos_y): logic_error = 1 if (v_end_x < 0 or v_end_x > max_pos_x): logic_error = 1 if (v_end_y < 0 or v_end_y > max_pos_y): logic_error = 1 if (v_start_x == v_end_x or v_start_y == v_end_y): logic_error = 1 if (v_d_time < min_drag_during_time or v_d_time > max_drag_during_time): logic_error = 1 if (v_d_num < min_drag_times_number or v_d_num > max_drag_times_number): logic_error = 1 if (v_d_i_time < min_drag_interval_time or v_d_i_time > max_drag_interval_time): logic_error = 1 if (logic_error == 1): error_message_prompt(logic_error_code) else: print_text.insert('end', "TestMethod: drag") print_text.insert( 'end', "滑动起始位置:(%d,%d) 滑动结束位置:(%d,%d)" % (v_start_x, v_start_y, v_end_x, v_end_y)) print_text.insert( 'end', "滑动持续时间: %f 滑动次数: %d 滑动间隔时间: %d" % (v_d_time, v_d_num, v_d_i_time)) except ValueError: if(start_x_entry.get() == '' or start_y_entry.get() == '' or end_x_entry.get() == '' or\ end_y_entry.get() == '' or d_time_entry.get() == '' or d_num_entry.get() == '' or\ d_i_time_entry.get() == '' ): error_message_prompt(empty_error_code) else: error_message_prompt(number_error_code) # print("TestMethod: drag ) Button(fm_drag, text="加入测试队列", command=click_b_drag_confirm).pack(pady=5) #随机滑动屏幕测试 v_r_d_num = 0 # 滑动的次数,默认为0 v_r_d_i_time = 1.0 #每两次滑动间隔的时间,秒为单位 fm_r_drag = Frame(root) label_fm_r_drag = Label(fm_r_drag, bg='white', text='随机滑动屏幕测试', font=('黑体', 12)) label_fm_r_drag.pack(fill='x', pady='5') r_d_num = Label(fm_r_drag, text='滑动的次数:', pady=5) r_d_num.pack(side='top') r_d_num_text = StringVar() r_d_num_entry = Entry(fm_r_drag, textvariable=r_d_num_text) r_d_num_text.set("") r_d_num_entry.pack(side='top', pady=5) r_d_i_time = Label(fm_r_drag, text='每两次滑动间隔的时间,秒为单位:', pady=5) r_d_i_time.pack(side='top') r_d_i_time_text = StringVar() r_d_i_time_entry = Entry(fm_r_drag, textvariable=r_d_i_time_text) r_d_i_time_text.set("") r_d_i_time_entry.pack(side='top', pady=5) def click_b_r_drag_confirm(): try: v_r_d_num = int(r_d_num_entry.get()) v_r_d_i_time = float(r_d_i_time_entry.get()) fm_r_drag.forget() fm_choose.pack() logic_error = 0 if (v_r_d_num < min_drag_times_number or v_r_d_num > max_drag_times_number): logic_error = 1 if (v_r_d_i_time < min_drag_interval_time or v_r_d_i_time > max_drag_interval_time): logic_error = 1 if (logic_error == 1): error_message_prompt(logic_error_code) print_text.insert('end', "TestMethod: random_drag") print_text.insert( 'end', "滑动次数: %d 滑动间隔时间: %f" % (v_r_d_num, v_r_d_i_time)) # print("TestMethod: random_drag 滑动次数: %d 滑动间隔时间: %f"%(v_r_d_num, v_r_d_i_time)) send('random_drag', 0, 0, 0, 0, v_r_d_num, v_r_d_i_time, 1, 0) except ValueError: if (r_d_num_entry.get() == '' or r_d_i_time_entry.get() == ''): error_message_prompt(empty_error_code) else: error_message_prompt(number_error_code) Button(fm_r_drag, text="加入测试队列", command=click_b_r_drag_confirm).pack(pady=5) def click_start_b(): nonlocal fin_in_b nonlocal b_con_phone nonlocal b_con nonlocal fm_con nonlocal b_choose nonlocal fm_choose nonlocal fm_touch nonlocal fm_r_touch nonlocal fm_drag nonlocal fm_r_drag if (bool_ever_click_connect_button == 0): error_message_prompt(have_not_connect_error_code) return if (bool_is_device_connected_successful == 0): error_message_prompt(not_successful_connected_error_code) return fin_in_b.forget() b_con_phone.forget() fm_con.forget() b_con.forget() fm_choose.forget() b_choose.forget() fm_touch.forget() fm_r_touch.forget() fm_drag.forget() fm_r_drag.forget() start_b.pack(side='top', fill='x') pause_b.pack(side='top', fill='x') resume_b.pack(side='top', fill='x') stop_b.pack(side='top', fill='x') return_in_b.pack(side='bottom', fill='x') def click_return_in_b(): nonlocal b_con nonlocal b_choose nonlocal fin_in_b nonlocal start_b nonlocal pause_b nonlocal resume_b nonlocal stop_b nonlocal return_in_b start_b.forget() pause_b.forget() resume_b.forget() stop_b.forget() return_in_b.forget() b_con_phone.pack(fill='x') b_con.pack(fill='x') b_choose.pack(fill='x') fin_in_b.pack(fill='x', side='bottom') fin_in_b = Button(root, text='队列输入完毕', font=('黑体', 12), height=2, command=click_start_b) fin_in_b.pack(side='bottom', fill='x') start_b = Button(root, text='开始测试', font=('黑体', 12), height=2, command=start) # 开始按钮 pause_b = Button(root, text='暂停测试', font=('黑体', 12), height=2, command=pause) # 暂停按钮 resume_b = Button(root, text='继续测试', font=('黑体', 12), height=2, command=resume) # 继续按钮 stop_b = Button(root, text='终止测试', font=('黑体', 12), height=2, command=stop) # 终止按钮 return_in_b = Button(root, text='返回队列输入界面', font=('黑体', 12), height=2, command=click_return_in_b) # 继续输入按钮 root.mainloop() '''except:
command=lambda: BTime1(channel1)) b.pack(side=LEFT, padx=5, pady=5) b = Button(frame3, text="+Time", width=Buttonwidth2, command=lambda: BTime2(channel1)) b.pack(side=LEFT, padx=5, pady=5) b = Button(frame3, text="-CH1", width=Buttonwidth2, command=lambda: BCHlevel1(channel1)) b.pack(side=LEFT, padx=5, pady=5) b = Button(frame3, text="+CH1", width=Buttonwidth2, command=lambda: BCHlevel2(channel1)) b.pack(side=LEFT, padx=5, pady=5) # Devicebox2=ttk.Combobox(frame1, width=Buttonwidth1, postcommand=ReadInDevice, values=Devicename2, ) # Devicebox2.pack(side=RIGHT, padx=5, pady=5) # Devicebox2.bind("<<ComboboxSelected>>",change_1) #l = Label(frame1,text="Devices:",background="#000080",fg="#ffffff") #l.pack(side=RIGHT, padx=5, pady=5) title.trace_variable('w', BSetup) if __name__ == '__main__': root.update() _thread.start_new(generate, ()) AUDIOin()
def testSphereMesh(self): for i in range(6,8): thread.start_new(createMesh,(10.0,(i+1)*20)) time.sleep(10)
ser = serial.Serial( usb, baudrate=BAUDRATE, ) while True: data = '' try: if usb != '': data = ser.readline() data = data.decode().replace('\r\n', '') if 'Soil Moisture Value 1 ' in data: print('data sensor A', int(data[23:])) else: print('data sensor B', int(data[23:])) else: raise SerialException except SerialException: ports = serial.tools.list_ports.comports(include_links=False) for port in ports: ser = serial.Serial( port.device, baudrate=BAUDRATE, ) if ser.isOpen(): usb = port.device break _thread.start_new(listeningArduino, ()) while True: pass
def initall_ev(): init() _thread.start_new(mainloop, ())
def testSphereMesh(self): for i in range(6, 8): thread.start_new(createMesh, (10.0, (i + 1) * 20)) time.sleep(10)
# Thread operations: # in Python 3,thread function has been renamed as _thread import _thread import time def print_time(threadName, delay): count = 0 while count <= 5: time.sleep(delay) count += 1 print(threadName, time.ctime(time.time())) try: _thread.start_new(print_time, ( "thread-1", 2, )) _thread.start_new(print_time, ( "thread-2", 4, )) except: print("unable to start the new threads") while 1: pass
def defender_rep_a(self): if self.uid_entry.get(): _thread.start_new(caller_backend.be_defender_reprovision, (self.uid_entry.get(), 'android', self.urls)) else: self.no_user_entered()
def _clickwin(self, event): """Prepares variables for _dragwin function""" self.offsetx = self.winfo_pointerx() - self.winfo_x() self.offsety = self.winfo_pointery() - self.winfo_y() def _dragwin(self, event): """Updates window position""" x = self.winfo_pointerx() - self.offsetx y = self.winfo_pointery() - self.offsety self.geometry('+%d+%d' % (x, y)) if __name__ == '__main__': customfont.loadfont(resource_path("fnt/Roboto-Regular.ttf")) customfont.loadfont(resource_path("fnt/Roboto-Light.ttf")) customfont.loadfont(resource_path("fnt/Roboto-Bold.ttf")) customfont.loadfont(resource_path("fnt/Roboto-Medium.ttf")) customfont.loadfont(resource_path("fnt/Roboto-Thin.ttf")) reminder = wgfunc.Reminder() root = Root() window = Window(root) window.lift() center_window(window) root.bind_mapping(window) start_new(window.logo_animation, ()) start_new(window.tab_switch, (window.active_tab, )) root.mainloop()
def testMultiQueryInterface(self): TestQueryInterface(0, 6) # When we use the custom interface in the presence of a long-lived # local server, i.e. a local server that is already running when # we request an instance of our COM object, and remains afterwards, # then after repeated requests to create an instance of our object # the custom interface disappears -- i.e. QueryInterface fails with # E_NOINTERFACE. Set the upper range of the following tests to 2 to # pass this tests, i.e. TestQueryInterface(1,2) TestQueryInterface(1, 6) def testDynamic(self): TestDynamic() def testGenerated(self): TestGenerated() if __name__ == '__main__': # XXX - todo - Complete hack to crank threading support. # Should NOT be necessary def NullThreadFunc(): pass import _thread _thread.start_new(NullThreadFunc, ()) if "-v" in sys.argv: verbose = 1 win32com.test.util.testmain()
def wrapper(*args, **kwargs): return _thread.start_new(f, args, kwargs)
smtpObj = smtplib.SMTP('localhost') smtpObj.sendmail(sender, receivers, message.as_string()) print ("邮件发送成功") except smtplib.SMTPException: print ("Error: 无法发送邮件") """ ## python3 多线程 def __dugu_thread(*args): for i in range(1, 10): print(time.time()) __dugu_thread() thread.start_new(__dugu_thread, ('thread1', 1)) print(threading.current_thread()) class MyThread(Thread): def __init__(self, count): Thread.__init__(self) self.count = count def run(self): for i in range(1, 3): print('thread', self.count) time.sleep(1) t = MyThread(5)
def goodlink_rep_i(self): if self.uid_entry.get(): _thread.start_new(caller_backend.be_goodlink_reprovision, (self.uid_entry.get(), 'iphone', self.urls)) else: self.no_user_entered()
def _common_path_listbox_callback(self, *args): self.tab_switch('Games') start_new(self._update_game_path, (CommonPaths.names_paths()[self.commonpaths_listbox.get('active')],))
def __init__(self, *args): winout.WindowOutput.__init__(*(self,)+args) self.hStopThread = win32event.CreateEvent(None, 0, 0, None) _thread.start_new(CollectorThread, (self.hStopThread, self))
def setUpClass(cls): _thread.start_new(start_tested_server, ('Server Thread',)) time.sleep(1)
TestVTable2() def testVTableMI(self): for i in range(3): TestVTableMI() def testMultiQueryInterface(self): TestQueryInterface(0,6) # When we use the custom interface in the presence of a long-lived # local server, i.e. a local server that is already running when # we request an instance of our COM object, and remains afterwards, # then after repeated requests to create an instance of our object # the custom interface disappears -- i.e. QueryInterface fails with # E_NOINTERFACE. Set the upper range of the following test to 2 to # pass this test, i.e. TestQueryInterface(1,2) TestQueryInterface(1,6) def testDynamic(self): TestDynamic() def testGenerated(self): TestGenerated() if __name__=='__main__': # XXX - todo - Complete hack to crank threading support. # Should NOT be necessary def NullThreadFunc(): pass import _thread _thread.start_new( NullThreadFunc, () ) if "-v" in sys.argv: verbose = 1 win32com.test.util.testmain()
# Wenn Motor A angeben wurde if (input_motor == "a"): # rufen wir die Funktion auf, die Motor A drehen lässt motorA(input_rotation, step_a) # Wenn Motor B angegeben wurde elif (input_motor == "b"): # Bis der Nutzer das Programm beendet while True: # rufen wir die Funktion auf, die Motor B drehen lässt motorB(input_rotation, step_b) # Wenn 'c' (beide Motoren) angeben wurde(n) else: # Wird ein Thread mit der Funktion Motor A in die gewünschte Richtung drehen zu lassen gestartet _thread.start_new(motorA, (input_rotation_a, step_a)) # die Funktion, um Motor B in die gewünschte Richtung drehen zu lassen, aufrufen motorB(input_rotation_b, step_b) # Wenn 'Strg + C' gedrückt wird beide Motoren ausschalten # und Nutzerbestätigung ausgeben except KeyboardInterrupt: for pin in pinsA: GPIO.output(pin, GPIO.LOW) for pin in pinsB: GPIO.output(pin, GPIO.LOW) print("Alle Pins aus!") print("Auf wiedersehen!") exit()