Python线程,线程不关闭

时间:2012-09-19 11:05:36

标签: python multithreading

我有一个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 关闭?

3 个答案:

答案 0 :(得分:5)

您需要使该线程成为守护程序线程。为此,在调用Thread的init

之后添加以下行
self.setDaemon(True)

当只有守护程序线程处于活动状态时程序将退出,主线程当然是非守护程序

答案 1 :(得分:3)

答案 2 :(得分:0)

我无法杀死我的python子进程,因为我在shell=True命令中设置了process.Popen选项。我删除了shell = True然后我可以杀了它。

如果子进程是shell,那么在shell结束之前你必须杀死正在运行的东西。