[英]Python threading, threads do not close
我有一個Python程序,當我用Ctrl-c退出應用程序時,腳本不會關閉。 我的過程仍顯示在運行的過程中。
#!/usr/bin/env python
import socket
import threading
import Queue
import serial
import mysql.connector
from datetime import datetime, date, time
host = '0.0.0.0'
port = 1024
buffer = 102400
my_queue = Queue.Queue()
class readFromUDPSocket(threading.Thread):
def __init__(self, my_queue):
threading.Thread.__init__(self)
self.my_queue = my_queue
def run(self):
while True:
buffer1,addr = socketUDP.recvfrom(buffer)
self.my_queue.put(buffer1)
print 'UDP received'
class readFromSerial(threading.Thread):
def __init__(self, my_queue):
threading.Thread.__init__(self)
self.my_queue = my_queue
def run(self):
while True:
buffer2 = ser.readline(eol=';')
if buffer2:
self.my_queue.put(buffer2)
print 'Serial received'
class process(threading.Thread):
def __init__(self, my_queue):
threading.Thread.__init__(self)
self.my_queue = my_queue
self.alive = threading.Event()
self.alive.set()
def run(self):
while True:
buffer3 = self.my_queue.get()
today = datetime.now()
timestamp = today.strftime("%A, %B %d, %Y %H:%M:%S")
print 'Data pushed at:', timestamp
print buffer3
if buffer3.startswith('temp:'):
temp = buffer3.replace('temp:','')
cnx = mysql.connector.connect(user='root', password='xxxxx', database='temperature')
cursor = cnx.cursor()
cursor.execute("INSERT INTO temperature.temperature (time,temperature) VALUES (%s, %s)", [timestamp, temp])
print 'Data inserted into Database'
cnx.commit()
cursor.close()
cnx.close()
if __name__ == '__main__':
# Create socket (IPv4 protocol, datagram (UDP)) and bind to address
socketUDP = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
socketUDP.bind((host, port))
ser = serial.Serial('/dev/ttyUSB0', 57600, timeout=2)
# Instantiate & start threads
myServer = readFromUDPSocket(my_queue)
mySerial = readFromSerial(my_queue)
myDisplay = process(my_queue)
myServer.start()
myDisplay.start()
mySerial.start()
while 1:
pass
UDPSock.close()
ser.close()
為什么python線程不能用Ctrl + c關閉?
您需要將線程設為守護程序線程。 為此,請在調用線程的init之后添加以下行
self.setDaemon(True)
當只有守護程序線程處於活動狀態時,程序將退出,主線程當然是非守護程序的
the_thread.setDaemon(true)
,請參見http://docs.python.org/library/threading.html#threading.Thread.daemon
我無法殺死我的python子進程,因為我在process.Popen
命令中設置了shell=True
選項。 我刪除了shell = True,然后將其殺死。
如果子進程是一個外殼程序,那么在外殼程序結束之前,您必須殺死它正在運行的東西。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.