当前位置: 首页>>代码示例>>Python>>正文


Python thread.exit函数代码示例

本文整理汇总了Python中thread.exit函数的典型用法代码示例。如果您正苦于以下问题:Python exit函数的具体用法?Python exit怎么用?Python exit使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了exit函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: sendData

def sendData(s):
	#have to tune it according to our data then will uncomment the lines
	log = open ('sendLog','r+')
	logs = log.readlines()
	line = int(logs[0])
	log.seek(0)
	log.write(str(int(line)+1))
	log.truncate()
	log.close()
	dataFile = open('databaseFile','r')
	dataFileLines = dataFile.readlines()
	data = dataFileLines[line]
	#convert required datafiles line into a tuple and save it as a json
	# send the json file this would make easier to feed into database at the server
	#data = "1,simple,list1"	
	print data[:-1]
	jsonfile = open('f','w')
	json.dump(data,jsonfile)
	jsonfile.close()
	jsonfile = open('f','r')
	data = jsonfile.read()
	k = len(data)
	for i in range(0,k,1024):
#		print data
		try:
			s.send(data[i:min(i+1023,k)])
		except socket.error:
			exit
	#s.send("\nDONE")
	jsonfile.close()
	thread.exit()
开发者ID:tvanicraath,项目名称:rapid,代码行数:31,代码来源:client.py

示例2: get_irc_socket_object

    def get_irc_socket_object(self):
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        sock.settimeout(10)

        self.sock = sock

        try:
            sock.connect((self.server['host'], self.server['port']))
        except:
            pp('Cannot connect to server (%s:%s).' % (self.server['host'], self.server['port']), 'error')
            sys.exit()

        sock.settimeout(None)

        sock.send('USER %s\r\n' % self.server['user'])
        sock.send('PASS %s\r\n' % self.server['oauthpass'])
        sock.send('NICK %s\r\n' % self.server['user'])

        if self.check_login_status(sock.recv(1024)):
            pp('Login successful.')
        else:
            pp('Login unsuccessful. (hint: make sure your oauth token is set in self.config/self.config.py).', 'error')
            thread.exit()
        
        self.join_channel()
        
        return sock
开发者ID:pandaforks,项目名称:pandacoder-aidraj-twitch-bot,代码行数:27,代码来源:irc.py

示例3: Pinging_Thread

	def Pinging_Thread(self):
		print "[+] Starting Ping thread"
		#self.ptc=threading.Condition()
		wait=True
		p=0.1
		while 1:							#loop forever
			if wait and (self.ping_delay > 0):					
				self.ptc.acquire()
				self.ptc.wait(self.ping_delay+self.penalty)		#send ping to server interval + penalty
				self.ptc.release()
				
			self.mutex_http_req.acquire()		#Ensure that the other thread is not making a request at this time
			try:
				resp_data=self.http.HTTPreq(self.url,"")	#Read response
				if self.verbose: self.http.v_print(pings_n=1)
				if self.penalty<60: self.penalty+=p	#Don't wait more than a minute

				if resp_data:								#If response had data write them to socket
					self.penalty=0
					if self.verbose: self.http.v_print(received_d_pt=len(resp_data))
					self.TunnaSocket.send(resp_data)		#write to socket
					resp_data=""							#clear data
					wait=False								#If data received don't wait
				else:
					wait=True
			except:
				self.TunnaSocket.close()
				thread.exit()
			finally:
				self.mutex_http_req.release()	
		print "[-] Pinging Thread Exited"
		#Unrecoverable
		thread.interrupt_main()		#Interupt main thread -> exits
开发者ID:AmesianX,项目名称:Tunna,代码行数:33,代码来源:TunnaClient.py

示例4: OnClose

	def OnClose(self,event):
		try:
			self.room.deleteFile()
		except:
			pass
		thread.exit()
		self.Close()
开发者ID:sjnov11,项目名称:Omok,代码行数:7,代码来源:OMOK_v1.39.py

示例5: write_socket_

def write_socket_(route_list):
	while(True):
		try:
			print 'Ready to send\n'
			str_msg = raw_input('\nMessage to Send (msg_str to_X) #> ')
			str_to_send = str_msg[:str_msg.find('to_')-1] #estracting message
			recive_node = str_msg[str_msg.find('_')+1:] #extracting node index
			global_command = str_msg
			if(str_msg == 'f'):
				print('Killing Threads...')
				thread.exit()
				break
			else:
				global_command = str_msg
				for element in route_list:
					try:
						if(str(element["Index"]) == recive_node):
							to_connect_addr = element["local"]
							print 'Node with ' + element["local"] + ' link local addres'
							s = socket.socket(socket.AF_INET6, socket.SOCK_RAW, socket.IPPROTO_TCP)
							s.connect((to_connect_addr, 9991,0,3))
							s.send(str_to_send + '\0')
							s.close()
						else:
							print "Element not in interop route list"
					except Exception,e: 
						print 'Error de escritura socket - Exception handler seeds: ' + str(e)
		except Exception,e: 
			print 'Error de escritura socket - Exception handler seeds: ' + str(e)
开发者ID:jmarcos-cano,项目名称:dockemu_interoperability,代码行数:29,代码来源:main_interop.py

示例6: run

 def run(self):
     "use paramiko sshclient to change passwords through ssh"
     ssh = paramiko.SSHClient()
     ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
     try:
         ssh.connect(self.ip_addr, username=self.username,
                     password=self.password)
     except socket.error:
         print "Connection refused on %s." % self.ip_addr
         thread.exit()
     except paramiko.AuthenticationException:
         print "wrong username and/or password %s." % self.ip_addr
         thread.exit()
     stdin, stdout, stderr = ssh.exec_command('passwd')
     if self.username == 'root':
         stdin.write('%s\n' % self.newpass)
         stdin.flush()
         stdin.write('%s\n' % self.newpass)
         stdin.flush()
         print stdout.readlines()
         print "password change on %s for user %s successfull" % \
             (self.ip_addr, self.username)
     else:
         stdin.write('%s\n' % self.password)
         stdin.flush()
         stdin.write('%s\n' % self.newpass)
         stdin.flush()
         stdin.write('%s\n' % self.newpass)
         stdin.flush()
         print stdout.readlines()
         print "password change on %s for user %s successfull" % \
             (self.ip_addr, self.username)
     ssh.close()
开发者ID:gi0cann,项目名称:sshpasswordchanger,代码行数:33,代码来源:sshpasschanger.py

示例7: take_a_video_picture_interval

def take_a_video_picture_interval(string,sleeptime,*args):
	global config_data
	global space
	while space<config_data.amount_of_space:	#while 1
		print string
		reload_config()
		comparison = check_config()	
		GPIO.setwarnings(False) #to remove Rpi.GPIO's warning
		if comparison:
			take_the_moment()			
			if config_data.motion_event and config_data.ext_int_event_a:					
				GPIO.setmode(GPIO.BOARD) 
				#GPIO.gpio_function(7) check if gpio is already setted as input or other
				GPIO.setup(7,GPIO.IN,pull_up_down=GPIO.PUD_DOWN) #pull-up input ,pull_up_down=GPIO.PUD_DOWN
				# dimensione della directory
				#print os.path.getsize("nomefile")
				#print os.stat(".").st_size
				#print sum(os.path.getsize(f) for f in os.listdir('.') if os.path.isfile(f)) #directory size without subdirectories
				print ("Debug 1: input value ")
				print GPIO.input(7)	
				GPIO.add_event_detect(7,GPIO.RISING,callback=take_a_video_picture_movement,bouncetime=3000) #bouncetime tempo inibizione tra un evento e un altro 3000=3s			
				thread.exit()
			else:
				GPIO.cleanup()
				time.sleep(sleeptime)
						
		else:
			print "The date/time range is not valid"
		
		
	print "There isn't space available - Max amount_of_space reached: "+str(config_data.amount_of_space)+" KB" 	
开发者ID:Maugir,项目名称:IProtectYou,代码行数:31,代码来源:rasp_cam_hhd_online.py

示例8: guess_rserver_data_length

    def guess_rserver_data_length(self):
        code = self.rserver_head_obj.get_http_code()
        try:
            c_method = self.client_head_obj.get_http_method()
        except AttributeError:
            # Problem with remote end of connection
            self.logger.log('*** Exception getting http code from client_head_obj -- remote end closed connection??\n')
            thread.exit()

        if code == '304' or code == '204' or code[0] == '1':
            self.rserver_all_got = 1
            self.rserver_data_sent = 1
            self.rserver_data_length = 0
            self.logger.log('*** Remote server response is %s and it must not have any body.\n' % code)

        # we had problem here if the responce was some kind of error. Then there may be
        # some body.
        # This time let's try to check for 4** responses to fix the problem.
        if (c_method == 'HEAD' or c_method == 'CONNECT') and (code[0] != '4'):
            self.rserver_all_got = 1
            self.rserver_data_sent = 1
            self.rserver_data_length = 0
            self.logger.log("*** Remote server response to the '%s' request. It must not have any body.\n" % c_method)

        if not self.rserver_all_got:
            try:
                self.rserver_data_length = int(self.rserver_head_obj.get_param_values('Content-Length')[0])
                self.logger.log("*** Server 'Content-Length' found to be %d.\n" % self.rserver_data_length)
                if self.rserver_data_length == 0:
                    self.rserver_all_got = 1
                    self.rserver_data_sent = 1
            except:
                self.rserver_data_length = 0
                self.logger.log("*** Could not find server 'Content-Length' parameter.\n")
开发者ID:JohannesBuchner,项目名称:digestaps,代码行数:34,代码来源:proxy_client.py

示例9: conectado

def conectado(con, cliente):
    respHost = con.recv(1024)
    #print respHost
    if armazena(respHost, con):
        con.sendall('Cadastro já extistente. Tente outro nome...')
        con.close()
        return
    else:
        print respHost+'  :conectou ao Servidor...'
        con.sendall(respHost+" Conectado...")

    if respHost == ' ':
        return
    if len(LISTA_DE_CLIENTES) == 1:
        con.send('Voce é o primeiro conectado, por favor, aguarde outras conexões para iniciar o chat')
    else:
        conectados(con)
    #print MAP_CLIENTES.values()
    while True:
        try:
            data = con.recv(1024)
            for x, m in MAP_CLIENTES.items():
                if con == m:
                    remetente = x
            if data:
               #broadcast_data(con, "\r"+ str(con.getpeername()) + 'disse: ' + data)
               broadcast_data_mapa(con,remetente+' disse: '+ data)
        except:
            print 'Finalizando conexão do cliente', cliente
            for x, m in MAP_CLIENTES.items():
                if m == con:
                    broadcast_data_mapa(con,'o cliente '+ x +' desconectou...')
                    del MAP_CLIENTES[x]
            con.close()
            thread.exit()
开发者ID:jorgejosejunior,项目名称:Chat_Para_SORedes,代码行数:35,代码来源:Servidor.py

示例10: new_thread

def new_thread(conn,ok):
    global close_serv
    while True:
        try:
            data = conn.recv(1024)
        except Exception as e:
            print "exception: {}".format(e)
            break
    
        if not data:
            print 'data is null'
        
        if data == 'exit':
            break
        
        if data == 'close_serv':
            print 'close server command is called'
            close_serv = True
        
        print 'data is ', data 
        
        conn.sendall('echo : ' + data)
    
    print 'prepare close connection and exit thread'
    conn.close()
    thread.exit()
    pass
开发者ID:phpxin,项目名称:pytools,代码行数:27,代码来源:echoserverdemo.py

示例11: get_client_access_token

  def get_client_access_token( self ):
    access_token_url = 'https://api.mapmyfitness.com/v7.0/oauth2/access_token/'
    access_token_data = {'grant_type': 'client_credentials',
              'client_id': self.client_id,
              'client_secret': self.client_secret}
    try:
      response = requests.post(url=access_token_url, data=access_token_data,
                  headers={'Api-Key': self.client_id})
    except:
      print 'Request for access token failed (not error code)'
      thread.exit()
      
    self.increment_calls()

    # Print out debug info if the call is not successful
    if( response.status_code != 200 ):
      print 'ERROR! Received a status code of ' + str(response.status_code) + '\n'
      print 'URL: ' + str(access_token_url) + '\n'
      print 'Data: ' + str(access_token_data) + '\n'
      print 'Received Content:'
      print response.content
      thread.exit()

    try:
      access_token = response.json()
    except:
      print 'Did not get JSON. Here is the response and content:'
      print response 
      print response.content 
      access_token = ''

    return access_token
开发者ID:fdac,项目名称:MapMyFitness,代码行数:32,代码来源:fitness_api.py

示例12: _connectToAClient

    def _connectToAClient(self):
        print 'New connection is waiting'

        conn, addr = self.sock.accept()
        self.currentUsers.append(addr)
        self.listenFlag = True

        print str(addr) + " is connected"

        hint = self._handleClientsMessage(None)
        conn.send(hint)

        while True:
            #get data from client
            data = conn.recv(1024)
            if not data:
                break
            print str(addr) + " " + str(data)

            #send back to the client
            conn.send( self._handleClientsMessage(data) )
            conn.send( self._handleClientsMessage(None))

        conn.close()
        for tmp in self.currentUsers:
            if tmp == addr:
                self.currentUsers.remove(tmp)
        thread.exit()
开发者ID:jxWho,项目名称:Chat,代码行数:28,代码来源:Ser.py

示例13: timer

def timer(no, interval):
    cnt = 0
    while cnt < 10:
        print 'Thread: (%d) Time:%s\n' % (no, time.ctime())
        time.sleep(interval)
        cnt += 1
    thread.exit()
开发者ID:coolspiderghy,项目名称:learning-python,代码行数:7,代码来源:test_start_new_thread.py

示例14: sendmail

def sendmail(fn,to,activeflag,xmobj,recipient,botaddress,pw,smtp_server):
    activeflag.value=1
    filename=fn
    
    msg = email.mime.Multipart.MIMEMultipart()
    msg['Subject'] =filename[filename.rfind('\\')+1:] 
    msg['From'] = botaddress
    msg['To'] = to
    
    
    body = email.mime.Text.MIMEText("""thekindlybot abides. Ask and the tunes are thine.""")
    msg.attach(body)       
    
    
    fp=open(filename,'rb')
    #att = email.mime.application.MIMEApplication(fp.read(),_subtype="mp3")
    att = email.mime.application.MIMEApplication(fp.read())
    fp.close()
    att.add_header('Content-Disposition','attachment',filename=filename)
    msg.attach(att)
    s = smtplib.SMTP(smtp_server)
    s.starttls()
    s.login(msg['From'],pw)
    s.sendmail(msg['From'],[msg['To']], msg.as_string())
    s.quit()
    activeflag.value=0
    xmobj.send_message(recipient, mbody='Mail Sent!')
    print 'mail sent! to ',recipient
    thread.exit()
开发者ID:thekindlyone,项目名称:thekindlybot,代码行数:29,代码来源:thekindlybot.py

示例15: www_connect_rserver

    def www_connect_rserver(self):
        self.logger.log('*** Connecting to remote server...')
        self.first_run = 0

        # we don't have proxy then we have to connect server by ourselves
        rs, rsp = self.client_head_obj.get_http_server()

        self.logger.log('(%s:%d)...' % (rs, rsp))

        try:
            s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            s.connect((rs, rsp))
            self.rserver_socket = s
            self.rserver_socket_closed = 0
            self.current_rserver_net_location = '%s:%d' % (rs, rsp)
            self.logger.log('Done.\n')
        except:
            self.rserver_socket_closed = 1
            self.logger.log('Failed.\n')
            self.exit()
            thread.exit()
        if self.client_head_obj.get_http_method() == 'CONNECT':
            self.logger.log('*** Generating server HTTP response...')
            buffer = 'HTTP/1.1 200 Connection established\015\012\015\012'
            self.rserver_head_obj, rest = http_header.extract_server_header(buffer)
            self.rserver_buffer = rest
            self.guess_rserver_data_length()
            self.logger.log('Done.\n')
开发者ID:JohannesBuchner,项目名称:digestaps,代码行数:28,代码来源:proxy_client.py


注:本文中的thread.exit函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。